Javascript只监听指定的最后一个节点上的事件 [英] Javascript listens for events only on the last node specified

查看:206
本文介绍了Javascript只监听指定的最后一个节点上的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在做一个简单的gui。问题是只有最后一个 textarea 似乎受脚本的影响。以前都不反应(检查截图)

$ p $ document.addEventListener(DOMContentLoaded,function(){

/ /交互式文字区域
变种txta = document.getElementsByTagName( 'textarea的');
为(VAR I = 0; I< txta.length;我++){
变种EARSE = txta [I ] .value;
console.log(earse); //调试
txta [i] .addEventListener('focus',function(e){
if(e.target.value = == earse){
e.target.value =;
e.target.addEventListener('blur',function(e){
if(e.target.value == =){
e.target.value = earse;
}
},false);
}
},false);
console .log(txta [i]); //调试
};

},false);

截图(



评论:您需要关闭内部循环varible earse 。因为每一步你都改变这个变数。


So I am working on a simple gui. The problem is that ONLY the last textarea seems be affected by the script. All the previous do not react at all. (check the screenshot)

document.addEventListener("DOMContentLoaded", function (){

// Interactive textareas
var txta = document.getElementsByTagName('textarea');
for (var i = 0; i < txta.length; i++){
    var earse = txta[i].value;
    console.log(earse); // debugging
    txta[i].addEventListener('focus', function(e){
        if (e.target.value === earse) {
            e.target.value = "";
            e.target.addEventListener('blur', function(e){
                if (e.target.value === "") {
                    e.target.value = earse;
                }
            }, false);
        }
    }, false);
    console.log(txta[i]); // debugging
};

}, false);

Screenshot (http://i.imgur.com/HTsMypB.jpg):

Html is just few simple textarea's with a value all specified in the html.

解决方案

Closure inside function:

document.addEventListener("DOMContentLoaded", function (){

// Interactive textareas
var txta = document.getElementsByTagName('textarea');
for (var i = 0; i < txta.length; i++){
    var earse = txta[i].value;
    console.log(earse); // debugging
    (function(earse){
            txta[i].addEventListener('focus', function(e){
                    if (e.target.value === earse) {
                            e.target.value = "";
                            e.target.addEventListener('blur', function(e){
                                    if (e.target.value === "") {
                                            e.target.value = earse;
                                    }
                            }, false);
                    }
            }, false);
        })(earse);
    console.log(txta[i]); // debugging
};

}, false);

http://jsfiddle.net/WjV8n/

For comment: You need closure varible earse inside loop. Because every step you change this varible.

这篇关于Javascript只监听指定的最后一个节点上的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆