jQuery .on() 有时有效,有时无效

Kri*_* O. 3 jquery jquery-on

我有奇怪的问题。起初我不想使用 .on() 方法,因为我根本无法让它工作,所以我使用了 .live()。

现在,我正在编写一个新的 jQuery 脚本,并且我大量使用了 .on() 并且它有效。到目前为止。

jQuery代码:

   $('#artistList a').on('click',function(e){
    console.log($(this).parent().text());
    e.preventDefault();
   });
Run Code Online (Sandbox Code Playgroud)

HTML代码:

<div id="artistList">
 <div class="artist"><a class="delete" href="#"></a>Psy</div>
 <div class="artist"><a class="delete" href="#"></a>Fernanda Martins</div>
 <div class="artist"><a class="delete" href="#"></a>DJ Nreal</div>
</div>
Run Code Online (Sandbox Code Playgroud)

也试过这个方法:

   $('#artistList>a').on('click',function(e){
   $('.delete').on('click',function(e){
Run Code Online (Sandbox Code Playgroud)

没运气。我错过了什么?

这是唯一不起作用的部分

我已经阅读了关于 .on() 的文档,并基于此,这应该有效。另外,我使用的是最新的 jQuery (jquery-1.8.3.min.js)。

编辑

<a>元素在 CSS 中有一个width: 15pxand height: 15px,所以它们是可见的。

tva*_*son 7

为了像live您一样工作,您需要将处理程序委托给更高级别的元素。

 $('body').on('click','#artistlist a', function(e) {
     // note the change to the selector to reflect your actual mark up
     // handler body
 });
Run Code Online (Sandbox Code Playgroud)

如果在初始加载页面后动态添加处理程序应应用到的元素,则需要使用这种形式的on。还要注意,处理程序应该在 DOM 加载后应用,方法是将脚本放在 body 元素的末尾之前,或者使用ready事件处理程序,$(function() { ... });

如果处理程序有时有效,有时无效,则很可能是加载到 DOM 中的元素与被调用的脚本之间的页面加载竞争条件。这通常表明您已省略在就绪事件处理程序中添加处理程序。