on() 方法在被選元素及子元素上添加一個(gè)或多個(gè)事件處理程序瘩扼。
自 jQuery 版本 1.7 起,on() 方法是 bind()春缕、live() 和 delegate() 方法的新的替代品茂洒。該方法給 API 帶來很多便利,我們推薦使用該方法凤巨,它簡化了 jQuery 代碼庫。
注意:使用 on() 方法添加的事件處理程序適用于當(dāng)前及未來的元素(比如由腳本創(chuàng)建的新元素)洛搀。
提示:如需移除事件處理程序敢茁,請(qǐng)使用off()方法。
提示:如需添加只運(yùn)行一次的事件然后移除留美,請(qǐng)使用one()方法彰檬。
語法
$(selector).on(event,childSelector,data,function)
參數(shù) 描述
event 必需伸刃。
規(guī)定要從被選元素移除的一個(gè)或多個(gè)事件或命名空間。
由空格分隔多個(gè)事件值逢倍,也可以是數(shù)組捧颅。必須是有效的事件。
childSelector 可選较雕。
規(guī)定只能添加到指定的子元素上的事件處理程序(且不是選擇器本身碉哑,比如已廢棄的 delegate() 方法)。
data 可選亮蒋。
規(guī)定傳遞到函數(shù)的額外數(shù)據(jù)扣典。
function
可選。規(guī)定當(dāng)事件發(fā)生時(shí)運(yùn)行的函數(shù)慎玖。
<!DOCTYPE html>
<html>
<head>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("div").on("click","p",{x:"a"},function(event){
alert(event.data.x);
$(this).slideToggle();
});
$("button").click(function(){
$("<p>This is a new paragraph.</p>").insertAfter("button");
});
});
</script>
</head>
<body>
<div style="background-color:yellow">
<p>This is a paragraph.</p>
<p>Click any p element to make it disappear. Including this one.</p>
<button>Insert a new p element after this button</button>
</div>
</body>
</html>
image.png
點(diǎn)擊確定
image.png