开发者

Execute href of an anchor, but not "onclick" of underlying DIV?

开发者 https://www.devze.com 2023-01-21 17:42 出处:网络
See the code/HTML snipped below. I have an anchor with an \"href\" which is inside a DIV with an \"onclick\" event handler. If I click the anchor, the browser opens a new tab and the \"onclick\" gets

See the code/HTML snipped below. I have an anchor with an "href" which is inside a DIV with an "onclick" event handler. If I click the anchor, the browser opens a new tab and the "onclick" gets executed. In case the user clicked the anchor, I want to supress the execution of "onclick". Returning "false" in an onclick of the anchor pevents the href being triggered. What's the solution here?

开发者_如何学JAVA
<html>
<head>
<script>
function clicky()
{
alert("Click!");
}
</script>
</head>
<body>
<div id="adiv" onclick="clicky()" style="border:1px solid black;background-color:red;width:400px;height:300px;">
<a href="http://www.gohere.but.dont.execute.onclick.com" target="_blank">a link</a>
</div>
</body>
</html>

René


Simplest way is to stop the propagation (bubbling) of the onclick event from the anchor tag to the div. Just add an onclick event to the anchor and set the handler to this:

event.cancelBubble = true; if(event.stopPropagation) { event.stopPropagation(); }

This is the cross-browser code. Tested in IE, FF, Chrome, Safari. So your code should look like this now:

<html>
<head>
<script>
function clicky()
{
alert("Click!");
}
</script>
</head>
<body>
<div id="adiv" onclick="clicky()" style="border:1px solid black;background-color:red;width:400px;height:300px;">
<a href="http://www.gohere.but.dont.execute.onclick.com" target="_blank" onclick="event.cancelBubble = true; if(event.stopPropagation) { event.stopPropagation(); }">a link</a>
</div>
</body>
</html>


Give your anchor an ID, and in the DIV's onclick handler, check if the target of the event was your anchor:

<div id="adiv" onclick="clicky(event)" style="border:1px solid black;background-color:red;width:400px;height:300px;">
<a id="link" href="http://www.gohere.but.dont.execute.onclick.com" target="_blank">a link</a>

<script>
function clicky(event) {
  event = event || window.event;
  var target = event.target || event.srcElement;
  if (target == document.getElementById('link'))
    return true;
  alert("Click!");
}
</script>
0

精彩评论

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