事件绑定在动态创建的元素和传递参数 [英] Event binding on dynamically created elements and passing parameters

查看:128
本文介绍了事件绑定在动态创建的元素和传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在为我的问题搜索解决方案时发现了类似的问题,但我不认为它是我正在寻找的。

使用jQuery的.on ()不是动态创建的元素上的绑定事件的困扰,但我被困住,而试图传递不同的参数来调用不同的函数。阅读 https://developer.mozilla.org/en/JavaScript/Guide/Closures我想出了以下工作示例,但我想知道它是否是最好的方法,或者是否有更优雅的解决方案?



< a href =http://jsfiddle.net/V25Zc/ =nofollow> http://jsfiddle.net/V25Zc/



另外我经常读到,使用eval()不是一个最佳实践,由于漏洞问题,但有另一种方法来构建动态函数名称?



编辑:



感谢大家的伟大答案!有没有一个答案被删除了?我喜欢那个,因为提示将参数存储在属性中。再次感谢所有!

解决方案

事件委托的点是你不需要绑定一个事件到每一个元素或多次到相同的元素),只需一次到普通父级,如下:

  function createLinks 
$ b var $ container = $(#container),
links =;



for(var i = 0; i< 4; i ++){
links + ='< a class =linklinkhref = #> Link_'+ i +'< / a>';
}

$ container.html(links).on(click,.linklink,function(){
console.log(fn action+ $ (this).index());
});
}

createLinks();

为避免使用 eval 一个函数数组,并通过索引调用它们:

  arrayOfFunctions [$(this).index()] 

http://jsfiddle.net/V25Zc/2/


I found similar questions while searching for a solution for my problem but I don't think its quite that what I'm looking for.

Using jQuery's .on() is no brainer for binding events on dynamically created elements, but I got stuck while trying to pass different parameters to call different functions. After reading https://developer.mozilla.org/en/JavaScript/Guide/Closures I came up with the following working example, but I would like to know if its the best way to do it or if there is a more elegant solution?

http://jsfiddle.net/V25Zc/

Plus I often read that using eval() isn't a best practice due to vulnerability issues but is there another way to build dynamic function names?

Edit:

Thanks a lot for everyone for the great answers! Did one of the answers got deleted though? I liked that one because of the hint to store the parameter in an attribute. Thanks again all!

解决方案

The point of event delegation is that you don't need to bind an event to every single element (or to the same element multiple times), just once to the common parent, like so:

function createLinks() {

    var $container = $("#container"),
        links = "";



    for (var i=0; i < 4; i++) {
        links += '<a class="linklink" href="#">Link_' + i + '</a>';
    }

    $container.html(links).on( "click", ".linklink", function(){
        console.log( "fn action"+$(this).index());
    });
}

createLinks();

To avoid using eval, you could have an array of functions and call them by index:

arrayOfFunctions[ $(this).index() ]();

http://jsfiddle.net/V25Zc/2/

这篇关于事件绑定在动态创建的元素和传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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