执行锚点的href,但不执行底层DIV的“onclick”?

时间:2010-10-20 15:01:04

标签: html javascript

请参阅下面的代码/ HTML剪辑。我有一个带有“href”的锚点,它位于带有“onclick”事件处理程序的DIV中。如果我单击锚点,浏览器将打开一个新选项卡并执行“onclick”。如果用户点击了锚点,我想要执行“onclick”。在锚的onclick中返回“false”会破坏href被触发。这里有什么解决方案?

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

2 个答案:

答案 0 :(得分:7)

最简单的方法是停止onclick事件从anchor标记到div的传播(冒泡)。只需向锚点添加一个onclick事件,并将处理程序设置为:

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

这是跨浏览器代码。在IE,FF,Chrome,Safari中测试过。 所以你的代码现在应该是这样的:

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

答案 1 :(得分:3)

给你的锚一个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>