简体   繁体   中英

jQuery functions don't work on the elements created 'on the fly'

I created some elements on the fly by JavaScript like this:

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).

This is my jQuery code:

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

You need to use live or delegate .

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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