简体   繁体   English

jQuery防止在单击内联href时div的单击行为

[英]jQuery Prevent div's click behavior when inline href is clicked

I have a div containing a href. 我有一个包含href的div。 The div has a jQuery live click event: div有一个jQuery live click事件:

$(".item").live("click", function() { 
    window.location = this.id;  
});

In the div I have a href: 在div中,我有一个href:

<div class="item" id="/test.html">
    <a href="javascript:void(0);" class="test" id="123">link</a>
</div>

Also with a live click event: 此外,还有现场点击事件:

$(".test").live("click", function() { 
    $(".item").unbind('click');
    alert(this.id);
});

What I try to achieve is click the div loads the div id as location while clicking the link inside the div does it's own thing while preventing the div click behavior. 我想要实现的是单击div将div ID作为位置加载,同时单击div中的链接确实是在防止div单击行为的同时做自己的事情。

I know I could take the href out of the div but I don's want that ;-) 我知道我可以将href排除在div外,但我不想要它;-)

UPDATED 更新

If you can, use jQuery 1.7 to do the event delegation using .on and stop the anchor clicks from propagating: 如果可以,请使用jQuery 1.7使用.on进行事件委派,并停止锚定点击的传播:

$(document).on("click","a.test", function(e) { 
    e.stopImmediatePropagation();
});

$(document).on("click","div.item", function(e) { 
    // whatever
});

http://jsfiddle.net/AuHjA/3/ http://jsfiddle.net/AuHjA/3/

Otherwise use .delegate instead of .live : 否则,请使用.delegate而不是.live

$(document).delegate("a.test", "click", function(e) { 
    e.stopPropagation();
});

$(document).delegate("div.item", "click", function(e) { 
    //whatever
});

http://jsfiddle.net/mblase75/AuHjA/4/ http://jsfiddle.net/mblase75/AuHjA/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM