JS中的事件默認是冒泡方式,逐層往上傳播,可以通過stopPropagation()函數停止事件在DOM層次中的傳播。如以下例子:
HTML代碼:
<!DOCTYPE html><html><head><meta charset="utf-8" /><title>stopPropagation()使用 - 瓊臺博客</title></head><body><button>button</button></body></html>[/code] 沒有加stopPropagation()[code]var button = document.getElementsByTagName('button')[0];button.onclick=function(event){ alert('button click');}; document.body.onclick=function(event){ alert('body click');}
DOM逐層往上傳播,所以單擊button按鈕也傳播到了body層,于是body層的click也響應了。結果彈出兩個警告框,分別是button與body。
加了stopPropagation()
var button = document.getElementsByTagName('button')[0];button.onclick=function(event){ alert('button click'); // 停止DOM事件層次傳播 event.stopPropagation();}; document.body.onclick=function(event){ alert('body click');}
在button的單擊事件處理函數中使用了stopPropagation()停止事件傳播函數,所以在彈出來自button單擊事件的警告框以后就傳播不到body,也就不會再次彈出body的警告框,結果只談一次警告框。
好多童鞋在寫JS的時候,往往忽視了DOM事件逐層往上傳播的特性,導致程序出現異常。如果需要了解更深入的知識可以找找有關JS事件冒泡的資料看看。
新聞熱點
疑難解答