"on"不绑定到动态添加的元素

lab*_*roo 6 jquery

我的HTML

<div>    
    <span  class="more-available" data-completeMessage="This is the complete message you see after clicking more">Hello</span>?
</div>
Run Code Online (Sandbox Code Playgroud)

我动态地在末尾添加一个锚标记,然后想要将一个点击处理程序附加到锚标记.所以我这样做

$(document).ready(function() {

   //Attach future proof click event to an anchor tag
   $('a.more').on('click', function() {
      var $parent = $(this).parent();
      $parent.text($parent.data('completemessage'));
   });

   //Add the anchor tag
   $('span.more-available').append($('<a class="more">...more</a>'));
});;?
Run Code Online (Sandbox Code Playgroud)

这不起作用.如果我用"live"替换"on"就行了.(但是现场折旧)

我知道我能做到这一点

$(document).ready(function() {

    $('div').on('click','a.more', function() {
        var $parent = $(this).parent();
        $parent.text($parent.data('completemessage'));
    });

    $('span.more-available').append($('<a class="more">...more</a>'));
});;?
Run Code Online (Sandbox Code Playgroud)

它有效,但我的问题是......

假设"on"提供了live的所有功能,我错了吗?"on"不会绑定到未来的元素吗?这是正确的行为,还是我做错了什么.

小提琴:http://jsfiddle.net/arishlabroo/pRBke/5/

Ali*_*guy 11

on()只是一个允许目标委派的绑定器.它更像是一个替代的delegate()live().

$('foo').live('click',fn); 本质上是 $(document).on('click','foo',fn);

考虑到这一点,您只需将click事件绑定到常量父包装器并委托给您的目标,如下所示:

$('span.more-available').on('click', 'a.more', function(){
    var $parent = $(this).parent();
    $parent.text($parent.data('completemessage'));
});
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢.它确实帮了很多:) (2认同)