jquery基本操作:jquery简单入门
绑定事件
给标签添加bind事件.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绑定事件</title>
<script src="jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function () {
var $button1=$("#button1");
var $p=$('.p');
$button1.bind("click",function () {$p.text('陈育能'); $p.slideToggle();});
});
</script>
</head>
<body>
<div class="div1">
<button id="button1">点击</button>
<p class="p">绑定事件</p>
</div>
</body>
</html>
要想绑定多个事件可以用:
$button1.bind({"click":function () {$p.text('陈育能');$p.slideToggle();},
"mouseenter":function () {$p.css("border","1px solid red")},
"mouseleave":function () {$p.css("border","0px solid red")}
});
解除事件
- 给bind解除bind事件用unbind()这个方法。
给click声明一个.pp命名空间。解除事件的时候就可以用unbind(‘.pp’),可以对多个事件定义相同的命名空间,这样就可以起到一次能够解除多个事件的效果;
$(document).ready(function () {
var $button1=$("#button1");
var $p=$('.p');
$button1.bind({"click.pp":function () {$p.text('陈育能');$p.slideToggle();},
"mouseenter":function () {$p.fadeIn(0)},
"mouseleave":function () {$p.fadeOut(0)}
});
$button1.unbind(".pp");
});
这样就可以对一个事件设置多个函数。然后通过unbind(“事件名”)来一键解除绑定事件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绑定事件</title>
<script src="jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function () {
var $button1=$("#button1");
var $p=$('.p');
$button1.bind("click",function () {$p.text('陈育能');$p.slideToggle();});
$button1.bind("click",function () {$p.fadeOut(0)});
$button1.bind("mouseenter",function () {$p.fadeIn()});
$button1.unbind('click');
});
</script>
</head>
<body>
<div class="div1">
<button id="button1">点击</button>
<p class="p">绑定事件</p>
</div>
</body>
</html>
但是不能通过这样设置,否者不能够在一个事件上添加多个函数。不然有效的函数只能是最后一个设置的。
$button1.bind({"click":function () {$p.text('陈育能');$p.slideToggle();},
"click":function () {$p.fadeOut(0)}
});
要想解除一个事件中的其中一个函数,可以这样:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绑定事件</title>
<script src="jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function () {
var $button1=$("#button1");
var $p=$('.p');
var fun1=function () {$p.text('陈育能');$p.slideToggle();};
var fun2=function () {$p.fadeOut()};
$button1.bind("click",fun1);
$button1.bind("click",fun2);
$button1.bind("mouseenter",function () {$p.fadeIn()});
$button1.unbind("click",fun1);
});
</script>
</head>
<body>
<div class="div1">
<button id="button1">点击</button>
<p class="p">绑定事件</p>
</div>
</body>
</html>
addClass常用来添加样式参数为样式的类名(标签的类)