gpt4 book ai didi

Jquery - 将委托(delegate)绑定(bind)到所有 "a"标签

转载 作者:行者123 更新时间:2023-12-01 00:53:46 24 4
gpt4 key购买 nike

当您单击 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 不适用于委托(delegate) - 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.

现在,如果您更改测试,请单击使用委托(delegate)并使用 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/

关于Jquery - 将委托(delegate)绑定(bind)到所有 "a"标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7751448/

24 4 0