简体   繁体   English

如何在js中动态添加事件

[英]how to add the event dynamicly in js

When I get some json data I want to display them in the page:当我得到一些 json 数据时,我想在页面中显示它们:

code:代码:

    function update(){

      for(far i=0;i<data.length;i++){
        var l=document.createElement("li"); 
        document.getElementById("ul_con").appendChild(l);
        l.onclick=function(){
          alert ("id:"+data[i].id);
        }

      }
}

However,I get the error: data[i]i is not defined.但是,我得到错误: data[i]i is not defined。

any way?反正?

BTW,since I post this question on my phone,so I can not format the code well.l hope someone can do me a favor.顺便说一句,因为我在手机上发布了这个问题,所以我不能很好地格式化代码。我希望有人能帮我一个忙。

UPDATE:更新:

    function update(){

      for(var i=0;i<data.length;i++){
        var l=document.createElement("li"); 
        l.tindex=i;
        document.getElementById("ul_con").appendChild(l);
        l.onclick=function(){
          alert ("id:"+data[this.tindex].id);
        }

      }
}

This code works also,but I wonder why the "data" can be used when the click event occur while the "i" can not?这段代码也有效,但我想知道为什么当点击事件发生时可以使用“数据”而“i”不能?

When the onclick event fires, the data[] array is out of context.onclick事件触发时, data[]数组脱离上下文。 You'll need to use this instead ie你需要改用this ,即

l.onclick=function(){
   alert ("id:"+this.id);
}

When the onclick function is called, it is at a much later time than when you hooked up the event handler and the data and i values may no longer be what they were at the moment you hooked up the function so you cannot rely on them.当 onclick function 被调用时,它比您连接事件处理程序时要晚得多,数据和 i 值可能不再是您连接 ZC1C425268E68384F1AB450 时的样子,因此您不能依赖它们。 In fact, the i value is guaranteed not to be the same because it will have advanced because of subsequent interations of the loop.事实上,i 值保证不会相同,因为它会因为循环的后续交互而提前。 The data value may or may not be valid depending upon the rest of your code.数据值可能有效也可能无效,具体取决于代码的 rest。

You can freeze them for use within the event handler like this:您可以冻结它们以在事件处理程序中使用,如下所示:

function update(){
    for(far i=0;i<data.length;i++){
        var l=document.createElement("li"); 
        document.getElementById("ul_con").appendChild(l);
        l.onclick=(function(mydata, index){     // define function that gets called at assignment time
            // variables mydata and index are available here in this scope
             return function() {
                alert ("id:"+mydata[index].id);
            };
       })(data, i);   // pass data and i into the inner scope
    }
}

By doing it this way, the first function(data,i) is executed at the time the onclick handler is assigned.通过这样做,第一个函数(data,i) 在分配 onclick 处理程序时执行。 This evaluates data and i and establishes their value for the use in the inner function via the function closure.这将评估数据和 i 并通过 function 闭包确定它们用于内部 function 的值。 See this writeup for a description and more examples.有关描述和更多示例,请参阅此文章 Since data is an array, you are not making a copy of it here (it is passed by reference) so you will have to make sure that its values are preserved until the time of the click handler (though it will not go out of scope because this closure preserves it).由于data是一个数组,因此您不会在此处复制它(它是通过引用传递的),因此您必须确保其值保留到单击处理程序的时间(尽管它不会 go 超出 scope因为这个闭包保留了它)。 The value of i is copied in the function parameter so you don't have to worry about the outer loop changing the value of i. i 的值被复制到 function 参数中,因此您不必担心外部循环会更改 i 的值。

It's a little less confusing and more easily understandable when it looks like this, but if you study the two, you can see that they are really the same thing, the first example just has an inline nameless function definition:当它看起来像这样时,它有点不那么令人困惑并且更容易理解,但是如果你研究这两者,你会发现它们真的是一回事,第一个例子只是有一个内联无名 function 定义:

function processMyClick(mydata, index) {
    return function() {
        alert ("id:"+mydata[index].id);
    };
}

function update(){
    for(far i=0;i<data.length;i++){
        var l=document.createElement("li"); 
        document.getElementById("ul_con").appendChild(l);
        l.onclick=processMyClick(data, i);
    }
}

If all you need is a couple pieces of data out of that data structure, then you may want to just put it on the DOM object itself like this:如果您只需要该数据结构中的几条数据,那么您可能只想将其放在 DOM object 本身上,如下所示:

function update(){
    for(far i=0;i<data.length;i++){
        var l=document.createElement("li"); 
        document.getElementById("ul_con").appendChild(l);
        l.myId = data[i];
        l.onclick=function() {alert(this.myId);};
    }
}

When putting data on DOM objects, you do have to be careful about cleaning up appropriately to avoid potential memory leaks or circular references if you create/destroy a lot of these and run in older browsers.将数据放在 DOM 对象上时,您必须小心进行适当的清理,以避免潜在的 memory 泄漏或循环引用,如果您创建/销毁其中很多并在旧浏览器中运行的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM