简体   繁体   English

在动态创建的元素上动态创建onclick事件

[英]Dynamic creation of onclick events on dynamically created elements

I'm trying to make a dynamically created navigation in which every element can be clicked and sent somewhere (don't worry about that). 我正在尝试进行动态创建的导航,在其中可以单击每个元素并将其发送到某个地方(不必担心)。 Here's my fragment of code: 这是我的代码片段:

        var navigation = $('<ul></ul>');
        for(a = 0; a < no_of_elements; a++) {
            navigation_content = $('<li></li>').click(function { send_me_to(a) });
            navigation_content.appendTo(navigation);
        }
        navigation.appendTo('.container');

Everything was working just fine until I added .click(...) in the 3rd line. 一切正常,直到我在第三行中添加.click(...)。 I also tried to split it into two lines, like so: 我还尝试将其分为两行,如下所示:

            navigation_content = $('<li></li>');
            navigation_content.click(function { send_me_to(a) });

...with no results, though. ...但是没有结果。 What is the proper way to bind click event to such elements? 将点击事件绑定到此类元素的正确方法是什么? Thanks in advance! 提前致谢!

In the function expression, you're missing the parenthesis () : 在函数表达式中,您缺少括号()

navigation_content = $('<li></li>').click(function() { send_me_to(a) });
//                                                ^^ missing

try this : 尝试这个 :

navigation_content.on('click',function(){
  send_me_to(a);
})

EDIT : Second solution: 编辑:第二个解决方案:

 navigation_content = $('<li id="li-link-'+a+'" data-id="'+a+'"></li>')

after "navigation.appendTo('.container');" 在“ navigation.appendTo('。container');”之后 add this code 添加此代码

$('li[id^="li-link"]').on('click' , function(){
send_me_to($(this).data('id'));
});

cheers. 干杯。

Not sure if the parentheses after the function keyword are mandatory, but the way you use a in the click handler will not have the result you expect. 不确定function关键字后的括号是否是必需的,但是在单击处理程序中使用a的方式将不会获得预期的结果。 You could do something like that: 您可以这样做:

navigation_content.click((function(aa) {
    return function() { send_me_to(aa); };
})(a));

jsFiddle Demo

I believe the issue is probably with sending a . 我认为问题可能出a It is probably only sending the last one since it isn't closed over. 由于未关闭,它可能只发送最后一个。 There is also a syntax error, the anonymous click function needs () after it 还有一个语法错误,它后面的匿名点击功能需要()

var navigation = $('<ul></ul>');
for(a = 0; a < no_of_elements; a++) {
 navigation_content = new function(){
  var copya = a;
  return $('<li></li>').click(function() { send_me_to(copya) });
 };
 navigation_content.appendTo(navigation);
}
navigation.appendTo('.container');

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

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