简体   繁体   English

执行锚的href,而不执行基础DIV的“ onclick”?

[英]Execute href of an anchor, but not “onclick” of underlying DIV?

See the code/HTML snipped below. 请参见下面的代码/ HTML。 I have an anchor with an "href" which is inside a DIV with an "onclick" event handler. 我有一个带有“ href”的锚,该锚位于具有“ onclick”事件处理程序的DIV中。 If I click the anchor, the browser opens a new tab and the "onclick" gets executed. 如果单击锚点,浏览器将打开一个新选项卡,并且将执行“ onclick”。 In case the user clicked the anchor, I want to supress the execution of "onclick". 万一用户单击锚点,我想禁止执行“ onclick”。 Returning "false" in an onclick of the anchor pevents the href being triggered. 在锚点事件的onclick中返回“ false”将触发href。 What's the solution here? 这里有什么解决方案?

<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. 最简单的方法是停止onclick事件从锚标记到div的传播(冒泡)。 Just add an onclick event to the anchor and set the handler to this: 只需将一个onclick事件添加到锚点,并将处理程序设置为此:

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

This is the cross-browser code. 这是跨浏览器的代码。 Tested in IE, FF, Chrome, Safari. 在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: 给您的锚点一个ID,然后在DIV的onclick处理程序中,检查事件的目标是否是您的锚点:

<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>

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

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