JQuery中阻止事件冒泡方式及其区别

 
更多

JQuery 提供了两种方式来阻止事件冒泡,下面就来说一下这两种方式以及具体的应用案例。

方式一:event.stopPropagation();

$("#div1").mousedown(function(event){
	event.stopPropagation();
});

方式二:return false;

$("#div1").mousedown(function(event){
	return false;
});

这两种方式区别如下:

return false 不仅阻止了事件往上冒泡,而且阻止了事件本身。event.stopPropagation() 则只阻止事件往上冒泡,不阻止事件本身。

具体应用场景: Google 的联想下拉框,当弹出下拉列表,用户在下拉列表区域按下鼠标时需要让光标仍然保持在文本输入框内。

示例测试代码: 当文本输入框获取焦点后,在div1的mousedown事件中采用 event.stopPropagation(); 代码,我们鼠标单击红色区域后文本输入框光标失去。而当我们使用 return false; 代码时,鼠标单击红色区域光标仍然停留在文本输入框内。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://www.phpernote.com/js/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$("#div1").mousedown(function(event){
		//event.stopPropagation();
		return false;
	});
	$("#div2").mousedown(function(event){
		alert("trigger mousedown event of rootDiv");
	});
});
</script>
</head>
<body>
<div id="rootDiv" style="position:relative;left:400px;top:200px;">
    <div>1.单击输入框,使输入框获取焦点:</div>
    <input id="input1" style="width:250px;" type="text"></input>
    <div id="div2">
        <div id="div1" style="width:200px;height:200px;background-color:red;"><br><br>2.然后再单击这里</div>
    </div>
</div>
</body>
</html>
打赏

本文固定链接: https://www.cxy163.net/archives/3869 | 绝缘体-小明哥的技术博客

该日志由 绝缘体.. 于 2014年01月21日 发表在 html, javascript, PHP, 编程语言 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: JQuery中阻止事件冒泡方式及其区别 | 绝缘体-小明哥的技术博客
关键字: , , , ,
【上一篇】
【下一篇】

JQuery中阻止事件冒泡方式及其区别:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter