jquery动态事件
添加事件
元素对象.bind("事件名",fn);//动态的给指定的元素追加指定的事件,多次点击将追加多个重复函数
移除事件
元素对象.unBind("事件名");
添加一次性事件:
添加的函数执行一次后失效
元素对象.one("事件名",fn)
页面载入事件:
注意不要写在函数里
$(document).ready(fn);fn表示函数对象function
页面载入成功后会调用函数对象。而且这个方式写多个,不会覆盖。
测试代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
<!
DOCTYPE
html>
<
html
>
<
head
>
<
meta
charset="utf-8">
<
title
>操作事件</
title
>
<!--
jquery动态事件
添加事件
元素对象.bind("事件名",fn);//动态的给指定的元素追加指定的事件,多次点击将追加多个重复函数
移除事件
元素对象.unBind("事件名");
添加一次事件:添加的函数执行一次后失效
元素对象.one("事件名",fn)
页面载入事件:注意不要写在函数里
$(document).ready(fn);fn表示函数对象function
页面载入成功后会调用函数对象。而且这个方式写多个,不会覆盖。
-->
<
script
src="js/jQuery-3.4.1.js" type="text/javascript" charset="utf-8"></
script
>
<
script
type="text/javascript">
//js动态添加事件
function testThing(){
var btn = document.getElementById("btn")
btn.onclick=function(){
alert("我是js方式")
}
}
//jQuery添加事件:以点击事件为例(click)
function testBind(){
$("#btn2").bind("click",function(){alert('我是bind绑定事件')})
}
//jQuery解绑事件
function testUnbind(){
$("#btn2").unbind("click");
}
//jQuery一次性事件
function testOne(){
$("#btn3").one("click",function(){alert("我是一次性事件")})
}
//页面加载事件:注意不要写在函数里
$(document).ready(function(){alert("我是页面加载事件")})
$(document).ready(function(){alert("我是页面加载事件2")})
</
script
>
</
head
>
<
body
>
<
h3
>操作事件</
h3
>
<
input
type="button" name="" id="" value="js动态添加事件" onclick="testThing()"/>
←连续点击也只添加一个函数(一个事件)
<
input
type="button" name="" id="" value="jquery动态添加事件" onclick="testBind()"/>
←连续点击添加多个函数(一个事件)
<
input
type="button" name="" id="" value="jquery解绑事件" onclick="testUnbind()" />
<
input
type="button" name="" id="" value="添加一次性事件jQuery-one()" onclick="testOne()"/>
←再次单击无效
<
hr
>
<
input
type="button" name="" id="btn" value="测试js" />
<
input
type="button" name="btn2" id="btn2" value="测试jquery-bind()" />
<
input
type="button" name="btn3" id="btn3" value="测试jQuery-one()" />
</
body
>
</
html
>
|