Jquery - 将委托绑定到所有“a”标签
当您单击 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);
});
i try to block the jq click()
when you click on an link in a div.
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);
});
This code works great but my content is dynamically so i need a delegate()
solution.
The code below dont work. But why? Whats the problem?
$('#all').delegate("a", "click", function(e)
{
e.stopPropagation();
e.preventDefault();
$('body').append(e.target.href);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
stopPropagation 不适用于委托 - http://api.jquery.com/event.stopPropagation/
现在,如果您更改测试点击以使用委托并使用 stopImmediatePropagation 它将起作用
http://jsfiddle.net/Lf3hL/14/
stopPropagation doesn't work with delegate - http://api.jquery.com/event.stopPropagation/
Now if you change your test click to use a delegate and use stopImmediatePropagation it will work
http://jsfiddle.net/Lf3hL/14/
因为
delegate()
的工作方式是让事件冒泡,然后在祖先元素上处理它们(在示例中为#all
)。因此,由于事件已经冒泡,因此您无法阻止它们在源头传播(因为它们必须传播才能工作)。
Because
delegate()
works by letting events bubble up, then handling them on the ancestor element (#all
in your example).So, because the events have already bubbled up, you can't stop them propagating at their source (because they must propagate to work).
来自 jQuery
.delegate()
文档:一种可能的解决方案是不在
a
上附加事件处理程序,而是在#test
上附加事件处理程序,并检查event.target
。我已经用这种方法更新了你的Fiddle。
From the jQuery
.delegate()
doc:One possible solution is not attaching the event handler on the
a
, but on#test
instead, and checking theevent.target
.I've updated your Fiddle with this method.
live 和 delegate 函数无法像“正常”事件一样处理
e.stopPropagation();
调用。来自委托 docs -The live and delegate functions are not able to handle the
e.stopPropagation();
call in the same way 'normal' events would. From the delegate docs -为什么不使用该
功能?
这将为正文完全加载后添加的所有标签添加点击功能。
why not use the
function?
that would add a click function to all the tags that are added after the body is fully loaded.