Javascript 单击live child时,如何禁用父项的onclick?
因此,当我需要在单击子对象时阻止父对象的默认操作时,通常只使用StopRopection。然而,这似乎不适用于活动元素。因此,我想在将孩子悬停在上面时暂时删除父对象的onclick属性。我似乎能够很好地删除它,但我似乎无法将它添加回元素。。。这就是我想到的Javascript 单击live child时,如何禁用父项的onclick?,javascript,jquery,hover,live,Javascript,Jquery,Hover,Live,因此,当我需要在单击子对象时阻止父对象的默认操作时,通常只使用StopRopection。然而,这似乎不适用于活动元素。因此,我想在将孩子悬停在上面时暂时删除父对象的onclick属性。我似乎能够很好地删除它,但我似乎无法将它添加回元素。。。这就是我想到的 $('body').delegate('.button', 'mouseenter mouseout', function(e){ if(e.type=='mouseenter'){ var inside
$('body').delegate('.button', 'mouseenter mouseout', function(e){
if(e.type=='mouseenter'){
var inside = $(this).parents('.post').attr('onclick');
$(this).parents('.post').attr('onclick','');
}else if(e.type=='mouseout'){
$(this).parents('.post').attr('onclick', inside);
}
})
因此,这将成功删除元素,但是尝试将其添加回总是不成功。。。它只是空出来的。有人能帮我一下吗?我完全卡住了。我也很乐意用其他方法来达到同样的效果。谢谢。试试这样:
if(e.type=='mouseenter'){
$(this).parents('.post').unbind('click');
}else if(e.type=='mouseout'){
$(this).parents('.post').bind('click');
}
//OR place your inside variable before if, like
var inside = $(this).parents('.post').attr('onclick'); //placed outside of if
if(e.type=='mouseenter'){
$(this).parents('.post').attr('onclick','');
}else if(e.type=='mouseout'){
$(this).parents('.post').attr('onclick', inside);
}
希望它对你有用试试这个:
$('div').live('click',函数(事件){
if($(event.target).hasClass('button'))
返回;
警惕(“你好”);
});
$('.a-span').live('click',函数(事件){
警报($(this.text());
});
$('div')。追加('other');
你好
世界
edited,尝试将“inside”变量放在if语句之外。仍然不起作用,onclick元素变成了这个@itdoell“我需要在单击子项时阻止父项的默认操作”我的代码按预期工作。但是你需要把它改写成你自己的代码。我不是这么说的。。。我说在一个活的元素上。。。这不是一个活动元素…好吧,我收回这一点,你的解决方案确实有效,只是我不想为所有的孩子阻止它,我只想为。按钮孩子阻止它。所以这个解决方案对我的情况来说似乎不实用。非常感谢。though@itdoell尝试此新版本,它将检查.button类
$('div').live('click', function(event) {
if ($(event.target).hasClass('button'))
return;
alert('hello');
});
$('.a-span').live('click', function (event) {
alert($(this).text());
});
$('div').append('<span class="a-span button">another</span>');
<div> hello <br/>
<span class="a-span">world</span>
</div>