13 - 绑定,移除事件
绑定
- eventName(fn);
编码效率略高/ 部分事件jQuery没有实现,所以不能添加 - on(eventName, fn);
编码效率略低/ 所有js事件都可以添加
注意点:
可以添加多个相同或者不同类型的事件,不会覆盖
示例代码:
<script>
$("button").click(function () {
alert("hello lnj");
});
$("button").click(function () {
alert("hello 123");
});
$("button").mouseleave(function () {
alert("hello mouseleave");
});
$("button").mouseenter(function () {
alert("hello mouseenter");
});
$("button").on("click", function () {
alert("hello click1");
});
$("button").on("click", function () {
alert("hello click2");
});
$("button").on("mouseleave", function () {
alert("hello mouseleave");
});
$("button").on("mouseenter", function () {
alert("hello mouseenter");
});
</script>
移除
- off方法如果不传递参数, 会移除所有的事件
$("button").off();
- off方法如果传递一个参数, 会移除所有指定类型的事件
$("button").off("click");
- off方法如果传递两个参数, 会移除所有指定类型的指定事件
$("button").off("click", test1);
示例代码:
<script>
$(function () {
function test1() {
alert("hello lnj");
}
function test2() {
alert("hello 123");
}
$("button").click(test1);
$("button").click(test2);
$("button").mouseleave(function () {
alert("hello mouseleave");
});
$("button").mouseenter(function () {
alert("hello mouseenter");
});
$("button").off();
$("button").off("click");
$("button").off("click", test1);
});
</script>
原文作者: 冯亚杰(DanBoard·Feng)
原文链接: http://danbo3110.github.io/2019/10/23/13 - 绑定,移除事件/
版权声明: 转载请注明出处(必须保留作者署名及链接)