Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript addEventListener为所有事件显示相同的值_Javascript_Json_Google Chrome Extension - Fatal编程技术网

Javascript addEventListener为所有事件显示相同的值

Javascript addEventListener为所有事件显示相同的值,javascript,json,google-chrome-extension,Javascript,Json,Google Chrome Extension,总之,我已经尝试了几个小时不同的事情,但我无法回避这个问题,我有一个接受JSON的函数- 我可以createElement('a'):很好 我可以设置所有元素属性,如href等:很好 我可以appendChild(a)和所需的元素标签:很好 但是我不能设置a.addEventListener(“click”,function(){alert(“clicked-”+a.id)},false)每次我单击任何href,它都会显示最后一个值 function setTags(tagsJson) {

总之,我已经尝试了几个小时不同的事情,但我无法回避这个问题,我有一个接受JSON的函数-

我可以
createElement('a')
:很好 我可以设置所有元素属性,如
href
等:很好 我可以
appendChild(a)
和所需的元素
标签
:很好 但是我不能设置
a.addEventListener(“click”,function(){alert(“clicked-”+a.id)},false)
每次我单击任何href,它都会显示最后一个值

function setTags(tagsJson) {

    var obj = JSON.parse(tagsJson); 
    var a = null;
    var linkText = null; 
    for (var i = 0; i < obj.length; i++) {
        if (typeof (obj[i].Tag_name) === 'undefined' || obj[i].Tag_name === null) {
           // DO NOTHING
        }
        else
        {   a = document.createElement('a');
            linkText = document.createTextNode(obj[i].Tag_name);
            a.appendChild(linkText);            
            a.href = "#";               
            a.textContent = obj[i].Tag_name;
            a.className = "badge badge-success";                                      
            document.getElementById("tags").appendChild(a);

          // HERE IS THE ISSUE
            a.addEventListener("click", function () { alert("clicked - " + a.textContent) }, false); 

       }
     }
}
function setTags(tagsJson){
var obj=JSON.parse(tagsJson);
var a=零;
var linkText=null;
对于(变量i=0;i
JSON具有以下值的示例

{“Tag\u id\”:12,“Tag\u name\”:“Aston Martin\”,{“Tag\u id\”:13,“Tag\u name\”:“Cars\”)“}

它应该在
textContent
处添加唯一的文本,如“Aston Martin”、“Auston”和“Cars”,但单击任何项目时,alter显示为
Cars
,尽管链接中的文本显示正确的值

根据上面的屏幕截图,我可以看到文本值很好,但是addEventListener只在单击时显示最后一个值

我想我对
addEventListener
的理解有误

我如何处理这个问题


干杯

而不是
a.textContent
使用
this.textContent

a.addEventListener("click", function () { alert("clicked - " + this.textContent) }, false); 

执行此事件侦听器时,for循环已经执行,直到满足
i
为止,这就是为什么
a
始终是最后一个。

而不是
a.textContent
使用
this.textContent

a.addEventListener("click", function () { alert("clicked - " + this.textContent) }, false); 

在执行此事件侦听器时,for循环已经执行,直到满足
i
为止,这就是为什么
a
始终是最后一个。

这是对闭包的典型误用

您在for循环之外声明了
a
变量,更重要的是在for循环中声明了click回调函数。因此,当您迭代时,
a
将被覆盖。最后,每次调用click函数时,
a
将其值设置为for循环期间设置的最后一个值

所以在你的情况下,你将永远

a.textContent = obj[obj.length - 1].Tag_name;
要使其按预期工作,您需要从单击事件本身检索您

a.addEventListener("click", function (event) { // use event here to find your element
   const a = document.getElementById(event.target.id); // This is the element that was clicked
   alert("clicked - " + a.textContent)
}, false);

这是对闭包的典型误用

您在for循环之外声明了
a
变量,更重要的是在for循环中声明了click回调函数。因此,当您迭代时,
a
将被覆盖。最后,每次调用click函数时,
a
将其值设置为for循环期间设置的最后一个值

所以在你的情况下,你将永远

a.textContent = obj[obj.length - 1].Tag_name;
要使其按预期工作,您需要从单击事件本身检索您

a.addEventListener("click", function (event) { // use event here to find your element
   const a = document.getElementById(event.target.id); // This is the element that was clicked
   alert("clicked - " + a.textContent)
}, false);

该函数仅在您单击该项时触发,因此当您单击该项时,它将接受在for循环外部声明的变量a,而a将保留循环中的最后一项

不要使用变量a,而是使用单词this将当前上下文添加到函数中

a.addEventListener("click", function () { alert("clicked - " + this.textContent) }, false); 

该函数仅在您单击该项时触发,因此当您单击该项时,它将接受在for循环外部声明的变量a,而a将保留循环中的最后一项

不要使用变量a,而是使用单词this将当前上下文添加到函数中

a.addEventListener("click", function () { alert("clicked - " + this.textContent) }, false); 

在for循环之后导致函数绑定

for (var i = 0;i<10;i ++){
    aLis[i].onclick = (function(num){
      return function(){
        alert(num)
      };                        
    })(i);    
}

for(var i=0;i导致for循环后的函数绑定

for (var i = 0;i<10;i ++){
    aLis[i].onclick = (function(num){
      return function(){
        alert(num)
      };                        
    })(i);    
}

for(var i=0;i之所以发生这种情况,是因为您编写警报函数的方式:

a.addEventListener("click", function(){
    alert("clicked - " + a.textContent);  // <---- THIS LINE
}, false); 
2:使用
这个

a.addEventListener("click", function(event){
    // event is an event object passed by the `addEventListener` function
    // where event.target === the DOM element that activates the listener
    alert("clicked - " + event.target.textContent);
}, false); 
a.addEventListener("click", function(){
    // `this` value === the element that activates this event listener.
    alert("clicked - " + this.textContent);
}, false); 
工作示例

var json=“[{\'Tag\u id\':12,\'Tag\u name\':\'Aston Martin\',{\'Tag\u id\':13,\'Tag\u name\':\'Cars\'”;
setTags(json);
函数集合标记(tagsJson){
var obj=JSON.parse(tagsJson);
var a=零;
var linkText=null;
对于(变量i=0;i
a{
显示:块;
}

发生这种情况是因为您编写警报函数的方式:

a.addEventListener("click", function(){
    alert("clicked - " + a.textContent);  // <---- THIS LINE
}, false); 
2:使用
这个

a.addEventListener("click", function(event){
    // event is an event object passed by the `addEventListener` function
    // where event.target === the DOM element that activates the listener
    alert("clicked - " + event.target.textContent);
}, false); 
a.addEventListener("click", function(){
    // `this` value === the element that activates this event listener.
    alert("clicked - " + this.textContent);
}, false); 
工作示例

var json=“[{\'Tag\u id\':12,\'Tag\u name\':\'Aston Martin\',{\'Tag\u id\':13,\'Tag\u name\':\'Cars\'”;
setTags(json);
函数集合标记(tagsJson){
var obj=JSON.parse(tagsJson);
var a=零;