javascript解決多事件衝突的問題(冒泡行爲、默認行爲)
(1)阻止多事件的冒泡
就是一個div包着以個input 相隔控件都被綁定了事件
你只想執行input控件的事件不想執行div事件
用下面這句話:
e.stopPropagation()
代碼塊:
$("input").bind(
"click",
function(event){
alert("hehe");
event.stopPropagation();
}
);
(2)阻止默認行爲
比如給一個submit控件綁定了click事件
但是隻想促發click不想促發提交submit事件
就用下面這句話:
e.preventDefault();
代碼塊:
$("input").bind(
"click",
function(event){
alert("hehe");
event.preventDefault();
}
);
(3)阻止默認行爲跟冒泡行爲
return false
代碼塊:
$("input").bind(
"click",
function(event){
alert("hehe");
return false;
}
);
就是一個div包着以個input 相隔控件都被綁定了事件
你只想執行input控件的事件不想執行div事件
用下面這句話:
e.stopPropagation()
代碼塊:
$("input").bind(
"click",
function(event){
alert("hehe");
event.stopPropagation();
}
);
(2)阻止默認行爲
比如給一個submit控件綁定了click事件
但是隻想促發click不想促發提交submit事件
就用下面這句話:
e.preventDefault();
代碼塊:
$("input").bind(
"click",
function(event){
alert("hehe");
event.preventDefault();
}
);
(3)阻止默認行爲跟冒泡行爲
return false
代碼塊:
$("input").bind(
"click",
function(event){
alert("hehe");
return false;
}
);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.