问题描述
请参阅下面的代码/ HTML。我有一个带有onclick事件处理程序的DIV内部的href的锚点。如果我点击锚点,浏览器会打开一个新选项卡并执行onclick。如果用户点击了锚点,我想抑制onclick的执行。在锚点的onclick中返回false会启动href。这里有什么解决方案?
< html>
< head>
< script>
函数clicky()
{
alert(Click!);
}
< / script>
< / head>
< body>
< div id =adivonclick =clicky()style =border:1px solid black; background-color:red; width:400px; height:300px;>
< a href =http://www.gohere.but.dont.execute.onclick.comtarget =_ blank>链接< / a>
< / div>
< / body>
< / html>
René
最简单的方法是停止从anchor标记到div的onclick事件的传播(冒泡)。只需将一个onclick事件添加到锚点,并将处理程序设置为此:
event.cancelBubble = true; if(event.stopPropagation){event.stopPropagation(); }
这是跨浏览器的代码。测试IE,FF,Chrome,Safari。
所以你的代码应该看起来像这样:
< html>
< head>
< script>
函数clicky()
{
alert(Click!);
}
< / script>
< / head>
< body>
< div id =adivonclick =clicky()style =border:1px solid black; background-color:red; width:400px; height:300px;>
< / div>
< / body>
< / html>
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?
<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>
这篇关于执行锚的href,但不是“onclick”底层的DIV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!