当我点击mainDiv时,将调用函数mainDiv()
,
当我点击subDiv时,会调用mainDiv()
和subDiv()
个函数。
单击subDiv时,我只想调用subDiv()
函数。我怎样才能做到这一点?
CODE:
<div onclick="mainDiv()">
show main div
<div onclick="subDiv()">
show sub div
</div>
</div>
<script type="text/javascript">
function mainDiv(){
alert("main div is clicked");
}
function subDiv(){
alert("sub div is clicked");
}
</script>
答案 0 :(得分:3)
除IE8(以及同一公司的旧版本)外,您可以在所有浏览器中使用stopPropagation。但是如果你想兼容,你应该使用解决方案described in quirksmode:
<div onclick="subDiv(event)">
function subDiv(e){
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
alert("sub div is clicked");
}
<强> Demonstration 强>
答案 1 :(得分:3)
使用e.stopPropogation()
<强> HTML 强>
<div onclick="subDiv(event)"> //<--- pass event parameter
<强>的javascrip 强>
function subDiv(e){
if(e.stopPropagation){ // check stoppropogation is avilable
e.stopPropagation(); //use stopPropogation
}else{
e.cancelBubble = true; // for ie8 and below
}
alert("sub div is clicked");
}
答案 2 :(得分:1)
<script type="text/javascript">
function mainDiv() {
alert("main div is clicked");
}
function subDiv(e) {
if (!e)
e = window.event;
//IE9 & Other Browsers
if (e.stopPropagation) {
e.stopPropagation();
}
//IE8 and Lower
else {
e.cancelBubble = true;
}
alert("sub div is clicked");
}
答案 3 :(得分:0)
试试这个
<div onclick="mainDiv()">
show main div
<div onclick="subDiv(event);">
show sub div
</div>
</div>
<script type="text/javascript">
function mainDiv(){
alert("main div is clicked");
}
function subDiv(arg){
arg.stopPropagation();
alert("sub div is clicked" + arg);
}
</script>
支持IE 8及更低版本使用arg.cancelBubble