开发者

How do I force the browser to only handle the top link if 2 elements are clickable?

开发者_运维知识库

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 IE
  • event.stopPropagation() is W3C
  • return false is to cancel the href link.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜