首先大家好,很抱歉我的英语。
当然,我并不完全理解事件处理程序中 return 的使用。
如果可能的话,我希望收到这方面的一些澄清。
在本文档中,我有一些嵌套元素 Fiddle .
每个元素都有一个事件处理程序,在冒泡阶段将相同的元素着色为红色。
我的问题是:为什么使用 jQuery 我可以通过 return false 来停止事件传播,而 javascript 我却不能做同样的事情?
任何建议都将很乐意阅读,谢谢大家。
<!DOCTYPE HTML>
<html>
<head>
<style>
.x{border-radius:250px;position: absolute;background-color:#CCC;border:1px solid #666;top: 24px; left: 24px;}
#el1{height: 200px;width: 200px;}
#el2{height: 150px;width: 150px;}
#el3{height: 100px;width: 100px;}
#el4{height: 50px;width: 50px;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// first snippet i can't use return false
function init(){
var elements = document.getElementsByClassName('x')
for(var i=0; i<elements.length; i++) {
elements[i].addEventListener('click',function(e){
this.style.backgroundColor='red'
alert("clik")
/*return false*/
},false)
/* return false*/
}
}
document.addEventListener('DOMContentLoaded',init,false);
// second snippet i can use return false
/*$(document).ready(function(){
$('div.x').click(function(){
$(this).css({'background-color':'red'})
alert("clik")
return false
})
})*/
</script>
</head>
<body>
<div id="el1" class="x">
<div id="el2" class="x">
<div id="el3" class="x">
<div id="el4" class="x"></div>
</div>
</div>
</div>
</body>
</html>
最佳答案
<a href = "http://stackoverflow.com/" id = "a">http://stackoverflow.com/</a>
$("#a").click(function(){
return false;
});
document.getElementById("a").onclick = function(){
return false;
}
document.getElementById("a").addEventListener("click",function(e){
e.stopPropagation();
e.preventDefault();
//the same function to "return false" in the above two method.
},false);
关于javascript - 事件处理程序返回 true Javascript jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23112723/