欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery中on綁定事件后引發(fā)的事件冒泡問題如何解決

 更新時間:2016年05月25日 14:23:17   作者:周XXXX  
這篇文章主要介紹了jQuery中on綁定事件后引發(fā)的事件冒泡問題及解決辦法,非常不錯,具有參考借鑒價(jià)值,感興趣的朋友一起看看吧

用on綁定時,我把子元素的 綁定到 document,而把父元素綁定到上級元素,導(dǎo)致 return false 阻止冒泡無效。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>事件冒泡</title> 
<script src="jquery-1.7.1.js" type="text/javascript"></script> 
<script language="javascript" type="text/javascript"> 
$(function () { 
$(document).on("click","#p1",function(e){ 
console.log(e.target.tagName); 
console.log("p1被點(diǎn)擊了"); 
//e.stopPropagation(); //終止冒泡的方法 
return false; 
}) 
$("#aa").on("click","#td1",function(e){ 
console.log(e.target.tagName); 
console.log("td1被點(diǎn)擊了"); 
}) 
$("#aa").on("click","#tr1",function(e){ 
console.log(e.target.tagName); 
console.log("tr1被點(diǎn)擊了"); 
}) 
$("#aa").on("click","#table1",function(e){ 
console.log(e.target.tagName); 
console.log("table1被點(diǎn)擊了"); 
}) 
}); 
</script> 
</head> 
<body id="aa"> 
<table onclick="alert('這是table')"> 
<tr onclick="alert('這是tr')"> 
<td onclick="alert('這是td')"> 
<p onclick="alert('這是p')">段落</p> 
</td> 
</tr> 
</table> 
<table id="table1"> 
<tr id="tr1"> 
<td id="td1"> 
<p id="p1">你好</p> 
</td> 
</tr> 
</table> 
</body> 
</html> 

on方法 將click等事件綁定在document對象上,頁面上任何元素發(fā)生的click事件都冒泡到document對象上得到處理。

增加了綁定效率。當(dāng)事件冒泡到document對象時,檢測事件的target,如果與傳入的選擇符(這里是button)匹配,就觸發(fā)事件,否則不觸發(fā)。

修改為統(tǒng)一綁定對象后即解決,初步認(rèn)為是因?yàn)?on方法的綁定機(jī)制問題。

所以return false 無效。子元素和父元素修改為相同 綁定元素后,問題解決

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>事件冒泡</title> 
<script src="jquery-1.7.1.js" type="text/javascript"></script> 
<script language="javascript" type="text/javascript"> 
$(function () { 
$("#aa").on("click","#p1",function(e){ 
console.log(e.target.tagName); 
console.log("p1被點(diǎn)擊了"); 
//e.stopPropagation(); //終止冒泡的方法 
return false; 
}) 
$("#aa").on("click","#td1",function(e){ 
console.log(e.target.tagName); 
console.log("td1被點(diǎn)擊了"); 
}) 
$("#aa").on("click","#tr1",function(e){ 
console.log(e.target.tagName); 
console.log("tr1被點(diǎn)擊了"); 
}) 
$("#aa").on("click","#table1",function(e){ 
console.log(e.target.tagName); 
console.log("table1被點(diǎn)擊了"); 
}) 
}); 
</script> 
</head> 
<body id="aa"> 
<table onclick="alert('這是table')"> 
<tr onclick="alert('這是tr')"> 
<td onclick="alert('這是td')"> 
<p onclick="alert('這是p')">段落</p> 
</td> 
</tr> 
</table> 
<table id="table1"> 
<tr id="tr1"> 
<td id="td1"> 
<p id="p1">你好</p> 
</td> 
</tr> 
</table> 
</body> 
</html> 

以上所述是小編給大家介紹的jQuery中on綁定事件后引發(fā)的事件冒泡問題及解決辦法,希望能夠幫助到大家!

相關(guān)文章

最新評論