0

我正在从外部 API 中提取一些数据,然后将其显示在仪表板页面中。为此,我会在处理完数据后生成 DOM 元素,如下所示:

for(var key in companies) {
    $(document.createElement("span"))
      .attr({ id: key })
      .appendTo($("#someDiv"))
      .click(function() {
          alert(key);
      });
      $("#"+key).html("<b>" + key + "</b>: $"+companies[key]+"<br>");
  }

但是,当我单击任何新生成的span元素时,我会收到一个警报,其中包含companies. 例如,如果我声明:

var companies = {
    "Google": 3,
    "Apple": 4
};

然后点击谷歌span和苹果span都会提醒4。我想要的行为是点击 Googlespan来提醒3

4

3 回答 3

3

这个怎么样:-

仅使用一次事件延迟附加事件处理程序on()。(参见添加的类compName)。并且只是使用它的id.

请参阅此处的委托事件处理程序参考。如果 somediv 已经存在于 DOM 中,那么你可以使用$('#someDiv').on('click','.compName',function(){...

$(function(){
$(document).on('click','.compName',function(){ 
//.....
   alert(this.id);
//....
});
....
for(var key in companies) {
    $(document.createElement("span"))
      .attr({ id: key, 'class':'compName' }).html("<b>" + key + "</b>: $"+companies[key]+"    
      <br>").html("<b>" + key + "</b>: $"+companies[key]+"<br>").
      .appendTo($("#someDiv"));

  }
//...
})
于 2013-05-11T18:43:01.880 回答
1

您需要key使用闭包来捕获该值,因为循环将在click处理程序实际执行时完成。尝试这个:

.click((function() {
    return function () {
        alert(key);
    };
})());

或者,您可以只使用alertid,因为您将其设置为:

.click(function () {
    alert(this.id);
});
于 2013-05-11T18:44:02.960 回答
0

那是因为变量键在你调用函数之前就被改变了。你需要一个闭包来防止它被外部代码修改:

for(var key in companies) {
    $(document.createElement("span"))
      .attr({ id: key })
      .appendTo($("#someDiv"))
      .click((function(privatekey) {
          return function(){
              alert(privatekey);
              };
      })(key));
      $("#"+key).html("<b>" + key + "</b>: $"+companies[key]+"<br>");
  }
于 2013-05-11T18:43:20.507 回答