一、jQuery添加事件的方式-1
重点:
jQuery事件处理方式-1
语法:jQuery对象.事件函数名([数据对象],callback);
[数据对象]:可选择参数,是一个对象数据。可以在事件处理函数中访问该数据。
补充:jQuery添加事件不会产生覆盖。
<div>hello</div>
<script>
var $div = $("div");
//没有数据实参的写法。
$div.click(function (e) {
//都获得了div中的内容。e是事件对象。
console.log (this.innerHTML);
console.log (e.currentTarget.innerHTML);
console.log (e.target.innerHTML);
console.log ($(this).html());
});
var obj = {
name:"empty",
age:20
};
//带有数据的写法
$div.click({
name:"empty",
age:20
},function (e) {
//都获得了div中的内容。e是事件对象。
//e.date 获得实参数据。
console.log (e.data);
console.log (e.data.name);
console.log (e.data["age"]);
});
</script>
二、jQuery添加事件的方式-2
jQuery事件添加方式-2
使用函数:bind 。对当前对象绑定指定的事件和事件处理函数。
1:给一个事件绑定一个事件处理函数。
语法:jQuery对象.bind(eventName,callback);
2: 给多个事件绑定一个事件处理函数。
语法:jQuery对象.bind(“eventName1 eventName2”,callback);
3: 多个事件绑定多个事件处理函数。
语法:jQuery对象.bind(对象);
对象:事件名和事件处理函数的集合。
<script src="js/jquery-1.12.4.js"></script>
<style>
div {
width: 200px;
height: 200px;
background-color: red;
}
</style>
<div>
hello
</div>
<script>
//bind - 1
$("div").bind("click",{
a:"a",b:"b"},function (e) {
console.log (e.data);
console.log ("你点击了我!");
});
//bind - 2
$("div").bind("mouseover mouseout" ,function (e) {
console.log ("你进入了我的世界,然后又离开了我的世界,我允许你进入我的世界,但是不能再我的世界进进出出!");
});
//bind - 3
$("div").bind({
mouseover:function () {
console.log ("正如我轻轻的来!");
},
mouseout:function () {
console.log ("轻轻的我走了!");
}
});
</script>
三、jQuery添加事件的方式-3
jQuery事件添加方式-3
事件代理:delegate
语法:jQuery对象.delegate(被代理的元素,事件名称,数据,callback)
<ul>
<li>11111</li>
<li>22222</li>
<li>3333</li>
<li>4444</li>
<li>5555</li>
</ul>
<script>
$("ul").delegate("li","click",{
a:"a",b:"b"},function (e) {
console.log (e.data);
console.log (e.target.innerHTML);
})
</script>
四、jQuery添加事件的方式-4(重点)
***重点:
on方法添加
1:一个事件绑定一个函数
语法:jQuery对象.on(eventName,[selector,data,] callback)
2:多个事件绑定一个函数。
语法:jQuery对象.on(eventNames,[selector,data,] callback)
3: 多个事件绑定多个函数。
语法:jQuery对象.on(对象)
参数:事件名称和事件处理函数的集合。
4: 替代代理事件。
语法:jQuery对象.on(eventNames,selector,[data,] callback)
<script src="js/jquery-1.12.4.js"></script>
<style>
div{
width: 200px;
height: 200px;
border: solid 1px;
}
</style>
</head>
<body>
<div>hello</div>
<ul>
<li>11111</li>
<li>22222</li>
<li>3333</li>
<li>4444</li>
<li>5555</li>
</ul>
<script>
//方法-1
$("div").on("click",{
a:"a",b:"b"},function (e) {
console.log ($(this).html());
console.log (e.data);
})
//方法-2
$("div").on("mouseover mouseout",function (e) {
console.log (e.type);//mouseover and mouseout
})
//方法-3
$("div").on({
mouseover:function () {
console.log ("轻轻的我又来了!");
},
mouseout:function () {
console.log ("轻轻的我离开了!");
}
});
//替代代理
$("ul").on(