Javascript 如何将onclick回调附加到div,而不是附加到div内部的链接上?
Html 当然,当我点击div中的任何地方时,它会执行“变魔术”。多亏了Javascript 如何将onclick回调附加到div,而不是附加到div内部的链接上?,javascript,jquery,events,hyperlink,click,Javascript,Jquery,Events,Hyperlink,Click,Html 当然,当我点击div中的任何地方时,它会执行“变魔术”。多亏了return false,如果我单击div中的任何链接,它仍然会执行“do magic”,并且不会更改页面,这是预期的行为 但是有一个链接被认为实际上改变了页面,所有者链接。问题是,使用我当前的设置,我阻止它工作。您需要停止从链接到父级.item\u容器的事件传播。 将此块添加到代码中: /** Bind the onclick only if you hover on the item since we got a
return false
,如果我单击div中的任何链接,它仍然会执行“do magic”,并且不会更改页面,这是预期的行为
但是有一个链接被认为实际上改变了页面,所有者链接。问题是,使用我当前的设置,我阻止它工作。您需要停止从链接到父级
.item\u容器的事件传播。
将此块添加到代码中:
/**
Bind the onclick only if you hover on the item since we got a lot
of items and several events and plugins to setup on them.
*/
$('.item_container').live('mouseenter', function(e){
$this = $(this);
if (!$this.data('isSetup')) {
$this.click(function(e){
// do magic
return false;
});
[... a lot of other stuff]
$this.data({'isSetup': true});
}
});
如果使用
e.preventDefault()
,是否也会这样做?请检查单击的元素类型。。。此标记名为.tagName。如果是链接,则不返回false…@2GDev:回答这个问题。如果它有效,您将获得repPerformance wise$('div.item\u container a.item\u owner')将是更好的选择。如果div中没有其他不应该停止传播的链接,这将非常有效。只有所有者链接必须触发页面更改。其他人不应该,点击他们应该执行'魔术'就像该地区的其余部分。谢谢。我对它做了一点改进,把它变成了$('a.item_owner',$this)。这个回调如何停止对另一个回调的检验?我不明白:它们是独立的函数!它只是停止触发click事件,并处理回调的取消
/**
Bind the onclick only if you hover on the item since we got a lot
of items and several events and plugins to setup on them.
*/
$('.item_container').live('mouseenter', function(e){
$this = $(this);
if (!$this.data('isSetup')) {
$this.click(function(e){
// do magic
return false;
});
[... a lot of other stuff]
$this.data({'isSetup': true});
}
});
$('.item_container a.item_owner').live('click', function(e){
e.stopPropagation();
});