简体   繁体   English

jQuery函数不适用于“即时”创建的元素

[英]jQuery functions don't work on the elements created 'on the fly'

I created some elements on the fly by JavaScript like this: 我通过JavaScript即时创建了一些元素,如下所示:

tmpString += '<a class="small_text add" id="' + variable_id + '_add" href="#" > add </a>';
$('#mydiv').html(tmpString);

Problem 问题

jQuery functions don't work on these 'on the fly' elements, but the same jQuery functions work on other normal elements (like "a" tags in my site menu). jQuery函数不适用于这些“即时”元素, 但是相同的jQuery函数适用于其他普通元素(例如,我的网站菜单中的“ a”标签)。

This is my jQuery code: 这是我的jQuery代码:

$('a').click(function(){ e.preventDefault(); alert(1); });

You need to use live or delegate . 您需要使用live委托

$('a').live('click', function() {
    //your code
});

live()用于动态添加的元素。

$('a').live("click", function(e){ e.preventDefault(); alert(1); });

每次您动态创建元素时,都应调用click处理器。

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

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