在使用jquery中,为元素绑定事件,通通常有以下几种方法
$(selector).event(function(){})
<selector onevnet="事件名"></selector>
$(selector).on('event名',[selector],function(){})
=======================================================================
No.1
$(selector).event(function(){})
适合为页面上已经存在的元素进行事件绑定
列如:
<button id="Btn">存在的按钮</button>
<script>
$('#Btn').click(function(){
alert('存在的绑定事件');
})
</script>
PS:事件要写在元素的下面,或者写在元素前不过要放在$(function(){})里
No.2
<selector onevnet="事件名"></selector>
这种适合:
动态创建的标签
特定某一/些的标签,需要把自身传入 onevent="事件名(this)"
例如:
扫描二维码关注公众号,回复:
2537022 查看本文章
<button id="Btn" >存在的按钮</button>
<script>
function Event(obj){
alert("Event事件的触发对象:"+obj);
}
$("#Btn").click(function(obj){
//创建一个按钮
var $input=$('<input type="text" onclick="Event(this)">');//为按钮绑定事件
$('body').append($input);
});
</script>
No.3
$(selector).on('event名',[selector],function(){})
适合为动态创建的元素绑定事件
<button id="Btn" >创建</button>
<script>
$("#Btn").click(function(obj){
//创建一个输入框
var $input=$('<input type="text">');
$('body').append($input);
});
$(document).on("click","input",function(){
alert('使用on绑定的事件');
})
</script>
Ps:
$(selector).on('event名',[selector],function(){}) 可以放在页面任一位置,可以在标签前,也可以在其后