jquery分开包装元素的onclick事件
我有一个div内的锚链接。 我希望锚链接和div分别处理onclick事件,但现在单击锚链接也会触发div的onclick事件。 我如何防止这种情况?
代码如下:
<html>
<head>
<style>
#box {
background-color: #ccffcc;
width: 400px;
height: 200px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#mailto").click(function(event) {
// correctly opens an email client if clicked
$("a[@href^='http']").attr('target','_blank');
return( false );
});
$("#box").click(function() {
// always goes to the home page, even if the #mailto id is clicked
window.location = '/index.php';
});
});
</script>
</head>
<body>
<div id="box">
<a href="mailto:someone@psomewhere.com" id="mailto">someone@psomewhere.com
</div>
</body>
</html>
有没有办法让我在加载mailto后停止执行代码?
谢谢!
约翰
您需要确保您的html有效,因此请关闭标签:
<a href="mailto:someone@psomewhere.com" id="mailto">someone@psomewhere.com<a/>
如果这仍然会导致问题,请尝试此操作。
$("#mailto").click(function(event)
{
event.stopPropagation();
if(event.srcElement == 'HTMLAnchorElement')
{
//Process
}
});
这可能是由于你的主播没有正确关闭。 或者它肯定不会有帮助
该事件冒泡了DOM树e.stopPropagation(); 将停止。
$("#mailto").click(function(event) {
event.stopPropagation();
// correctly opens an email client if clicked
$("a[@href^='http']").attr('target', '_blank');
return (false);
});
$("#box").click(function() {
// always goes to the home page, even if the #mailto id is clicked
window.location = '/index.php';
});
小提琴 http://jsfiddle.net/uwJXK/
关于stopPropagation() http://api.jquery.com/event.stopPropagation/
