在jQuery中动态地将监听器添加到ajax创建的内容中

dav*_*idP 4 ajax jquery bind listener

我想获取链接点击的html值.链接是使用Ajax动态创建的,所以我不认为.bind会工作,我没有.live的最新版本

$('div#message').click(function() {
  var valueSelected = $(this).html();  // picks up the whole id. I juust want single href!          
  alert(valueSelected);
  return false;
});



<div id="message">
<br/>
<a class="doYouMean" href="#">location A</a>
<br/>
<a class="doYouMean" href="#">location B</a>
<br/>
<a class="doYouMean" href="#">location C</a>
<br/>
<a class="doYouMean" href="#">location D</a>
<br/>
<a class="doYouMean" href="#">location E</a>
<br/>
</div>
Run Code Online (Sandbox Code Playgroud)

And*_*rew 16

这是一个未提及的替代方法:

如果您正在使用jQuery v1.7 +,则可以使用该.on()方法将事件侦听器绑定到当前HTML以及将来添加的HTML:

$('#message a').on('click', function(){
    alert('link clicked!');
});
Run Code Online (Sandbox Code Playgroud)

如果您使用的是旧版本的jQuery,建议您使用该.delegate()方法:

$('#message').delegate('a', 'click', function(){
    alert('link clicked!');
});
Run Code Online (Sandbox Code Playgroud)

综上所述:

$(elements).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(elements).on(events, selector, data, handler);        // jQuery 1.7+
Run Code Online (Sandbox Code Playgroud)