Say I have the following code:
<div onclick='location.href="http://www.example.com/"'>
<a href='#' onclick='alert("blah")'>click</a>
</div>
Is there a way to only have the anchor evaluated when I click the 'click' text and not have the div's onclick evaluated?
You can stop event propagation by returning false
from the anchor's click event handler.
<div onclick='location.href="http://www.example.com/"'>
<a href='#' onclick='alert("blah"); return false;'>click</a>
</div>
You've tagged this question with jQuery. In that case, you should be using unobtrusive Javascript so:
<div id="someid">
<a href="#">click</a>
</div>
with:
$(function() {
$("#someid").click(function() {
window.location.href = "http://www.example.com";
});
$("#someid a").click(function() {
alert("blah");
return false;
});
});
is a much cleaner solution.
See http://www.quirksmode.org/js/events_order.html.
<div onclick='location.href="http://www.example.com/"'>
<a href='#' onclick='alert("blah"); event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false;'>click</a>
</div>
event.cancelBubble
is for IEevent.stopPropagation()
is W3C- return false is to cancel the href link.
精彩评论