JavaScript中使用stopPropagation函数停止事件传播例子
JS中的事件默认是冒泡方式,逐层往上传播,可以通过stopPropagation()函数停止事件在DOM层次中的传播。如以下例子:
HTML代码:
<!DOCTYPEhtml> <html> <head> <metacharset="utf-8"/> <title>stopPropagation()使用-琼台博客</title> </head> <body> <button>button</button> </body> </html> [/code] 没有加stopPropagation() [code] varbutton=document.getElementsByTagName('button')[0]; button.onclick=function(event){ alert('buttonclick'); }; document.body.onclick=function(event){ alert('bodyclick'); }
DOM逐层往上传播,所以单击button按钮也传播到了body层,于是body层的click也响应了。结果弹出两个警告框,分别是button与body。
加了stopPropagation()
varbutton=document.getElementsByTagName('button')[0]; button.onclick=function(event){ alert('buttonclick'); //停止DOM事件层次传播 event.stopPropagation(); }; document.body.onclick=function(event){ alert('bodyclick'); }
在button的单击事件处理函数中使用了stopPropagation()停止事件传播函数,所以在弹出来自button单击事件的警告框以后就传播不到body,也就不会再次弹出body的警告框,结果只谈一次警告框。
好多童鞋在写JS的时候,往往忽视了DOM事件逐层往上传播的特性,导致程序出现异常。如果需要了解更深入的知识可以找找有关JS事件冒泡的资料看看。