如何在点击直播孩子时禁用父级的onclick?

时间:2012-01-13 04:47:28

标签: javascript jquery hover live

因此,当我需要在单击子项时阻止父项的默认操作时,我通常只使用stopPropegation。但是,这似乎不适用于实时元素。所以我有想法在孩子盘旋时暂时删除父母的onclick属性。我似乎能够将它删除就好了,但我似乎无法将它添加回元素......这就是我想出来的......

$('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);
        }
    })

所以这将成功删除元素,但是将其添加回来的尝试总是不成功...它只是空的。任何人都可以帮我一把吗?我完全卡住了。我也很乐意采用替代方法来实现相同的结果。谢谢。

2 个答案:

答案 0 :(得分:1)

试试这个http://jsfiddle.net/kDuNU/4/

$('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>

答案 1 :(得分:0)

尝试这样的事情:


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);
}

希望它适合你

相关问题