当前位置 : 主页 > 网页制作 > JQuery >

Jquery – 将委托绑定到所有“a”标记

来源:互联网 收集:自由互联 发布时间:2021-06-15
当你点击div中的链接时,我试图阻止jq click(). HTML div id="all" div id="test" a href="http://google.de"google/a /div/div JS $('#test').click(function() { alert('only when i click the div'); });$('a').click(function(e) { e.stopPr
当你点击div中的链接时,我试图阻止jq click().

HTML

<div id="all">
    <div id="test">
        <a href="http://google.de">google</a>
    </div>
</div>

JS

$('#test').click(function() { alert('only when i click the div');  });

$('a').click(function(e) {
    e.stopPropagation();
    e.preventDefault();
    $('body').append(e.target.href);
});

这段代码效果很好,但我的内容是动态的,所以我需要一个delegate()解决方案.
下面的代码不起作用.但为什么?有什么问题?

$('#all').delegate("a", "click", function(e)
{
    e.stopPropagation();
    e.preventDefault();
    $('body').append(e.target.href);
});


http://jsfiddle.net/Lf3hL/13/

stopPropagation不适用于委托 – http://api.jquery.com/event.stopPropagation/

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will propagate to the elements to which they are delegated; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false.

现在,如果您更改测试,请单击以使用委托并使用stopImmediatePropagation,它将起作用

$('#all').delegate('#test', 'click' ,function() {
    alert('only when i click on the div');
});    

$('#all').delegate("a", "click", function(e)
{
    e.stopImmediatePropagation();
    e.preventDefault();
    $('body').append(e.target.href);
});

http://jsfiddle.net/Lf3hL/14/

网友评论