2

假设我想在单击具有“data-change”属性的所有 span 标签时更改它们的 innerHTML:

$('span[data-change]').click(function(){
 $(this).text('Text was changed dynamically');
});

现在,如果我使用 jQuery on javascript 在我的 html 文档中添加一个带有 data-change 属性的新 span 标签,onclick 事件将不会在新添加的 span 标签上起作用。为什么?我怎样才能让它们工作?谢谢!

4

3 回答 3

2

在为动态元素注册事件时,您需要使用事件委托。

您可以使用.on()注册委托事件。

$(document).on('click', 'span[data-change]', function(){
    $(this).text('Text was changed dynamically');
});

你也可以阅读这个

于 2013-09-19T06:10:16.340 回答
1

您必须对动态创建的元素使用委托,如下所示:

$(document).on('click','span[data-change]',function(){
    $(this).text('Text was changed dynamically');
});

jQuery .on() API 页面有更多细节和示例。

于 2013-09-19T06:11:54.583 回答
1
 $(document).delegate('click', 'span[data-change]', function(){
  $(this).text('Text was changed dynamically');
});

或者

 $(document).on('click', 'span[data-change]', function(){
     $(this).text('Text was changed dynamically');
 });

更多信息

http://api.jquery.com/delegate/
http://jqfundamentals.com/chapter/events

于 2013-09-19T06:11:56.213 回答