Jquery给指定元素绑定事件
bind()
注意:bind()函数在jquery1.7版本以前比较受推崇,1.7版本出来之后,官方已经不推荐用bind()
:bind()函数只针对已经存在的元素进行事件的设置
- 介绍:bind() 方法为被选元素添加一个或多个事件处理程序,并规定事件发生时运行的函数
使用:绑定单个事件 模板: $(selector).bind(event,data,function)
This is a paragraph.
绑定多个事件写法 : 模板: $(selector).bind({event:function, event:function, …})
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").bind({
click:function(){$("p").slideToggle();},
mouseover:function(){$("body").css("background-color","red");},
mouseout:function(){$("body").css("background-color","#FFFFFF");}
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button>请点击这里</button>
</body>
</html>
Unbind()
介绍:unbind() 方法移除被选元素的事件处理程序。
该方法能够移除所有的或被选的事件处理程序,或者当事件发生时终止指定函数的运行
使用:去除p标签上所有事件 模板:$(selector).unbind(event,function)
这是一个段落。
这是另一个段落。
点击任何段落可以令其消失。包括本段落。
去除绑定的某一特定事件方式
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
function alertMe()
{
alert("Hello World!");
}
$(document).ready(function(){
$("p").click(alertMe);
$("button").click(function(){
$("p").unbind("click",alertMe);
});
});
</script>
</head>
<body>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<p>点击任何段落可以触发一个提示框。包括本段落。</p>
<button>从 p 元素的 click 事件删除提示框函数</button>
</body>
</html>
live() on() delegate()使用方式基本与bind()并且都支持未来新添加元素的事件设置
以live()为例
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").live("click",function(){//此处的live()改成bind(),新增的<p>标签就没有此事件,而live()依然存在此事件
$(this).slideToggle();
});
$("button").click(function(){
$("<p>This is a new paragraph.</p>").insertAfter("button");
});
});
</script>
</head>
<body>
<p>这是一个段落。</p>
<p>点击任意 p 元素会令其消失。包括本段落。</p>
<button>在本按钮后面插入新的 p 元素</button>
<p><b>注释:</b>通过使用 live() 方法而不是 bind() 方法,新的 p 元素同样会在点击时消失。</p>
</body>
</html>
现在更推荐使用on(),主讲on()
Reason:
bind()函数在jquery1.7版本以前比较受推崇,1.7版本出来之后,官方已经不推荐用bind(), 替代函数为on(), 这也是1.7版本新添加的函数,同样,可以用来代替live()函数,live()函数在1.9版本已经删除; c、bind()、.live() 或.delegate(),查看源码就会发现,它们实际上调用的都是.on()方法
使用on()对类选择器进行单事件绑定
2
3
4
5
6
7我是原生div
8
9
10
还没有评论,来说两句吧...