jq 事件机制
**绑定事件**
法一: 数组对象.bind("去掉on的事件名",绑定内容) 追加模式,一个事件增加多个操作,js是覆盖,可配合js追加绑定
function t2()
{
$("#btn2").bind("click",function(){alert("我是bind绑定单击事件")});
$("#btn2").bind("click",function(){alert("第二个绑定")});
}
多个事件绑定相同函数
数组对象.bind('去掉on的事件名' '去掉on的事件名',函数);
多个事件绑定不同函数
数组对象.bind({'去掉on的事件名':函数,'去掉on的事件名':函数,...});
法二:
$(选择器).去掉on的事件名(函数)
function(){
$("#b1").click(function(){alert("hh")})
}
**支持链式绑定**
$('选择器').去掉on的事件(函数).去掉on的事件(函数).去掉on的事件(函数);
最后以分号结尾
**解除绑定**
数组对象.unbind("去掉on的事件名") 去除绑定的所有指定事件,不能运用于js
function t3()
{
$("#btn2").unbind("click");
}
**one事件**
数组对象.one("去掉on的事件名",执行内容) 一次性绑定,事件执行后自动解绑
function t4()
{
$("#btn3").one("click",function(){alert("我是one")});
$("#btn3").one("click",function(){alert("我是one2")});
}
**页面载入事件**
在页面加载时执行,无需放进body中
js方式
会存在相同事件覆盖的问题
window.事件=函数
window.onload=function(){alert("js方式一")}
window.onload=function(){alert("js方式二")}
window.onclick=function(){alert("js方式三")}
jq方式
相同事件会绑定,不会覆盖
法一:$(document).ready(函数)
$(document).ready(function(){alert("jq方式一")})
$(document).ready(function(){alert("jq方式二")})
法二:$(函数)
$(function(){alert($("ul>label").html())})
代码示例:
<html>
<head>
<meta charset="utf-8">
<title>jq 事件</title>
<script type="text/javascript" src="js/jquery-3.4.1.js" charset="UTF-8"></script>
<script type="text/javascript">
function t1()
{
var btn=document.getElementById("btn");
btn.onclick=function(){
alert("js");
}
}
function t2()
{
$("#btn2").bind("click",function(){ alert("我是bind绑定单击事件")});
$("#btn2").bind("click",function(){ alert("第二个绑定")});
}
function t3()
{
$("#btn2").unbind("click");
}
function t4()
{
$("#btn3").one("click",function(){ alert("我是one")});
$("#btn3").one("click",function(){ alert("我是one2")});
}
//页面载入
window.onload=function(){ alert("js方式")}
window.onload=function(){ alert("js方式2")}
//jQuery
$(document).ready(function(){ alert("jq 方式一")})
$(document).ready(function(){ alert("jq 方式二")})
</script>
<style type=css>
</style>
</head>
<body>
<input type="button" value="测试js" onclick="t1()" />
<input type="button" value="测试绑定" onclick="t2()" />
<input type="button" value="测试动态解绑" onclick="t3()" />
<input type="button" value="测试one" onclick="t4()"/>
<hr />
<input type="button" value="测试js" id="btn"/>
<input type="button" name-"btn2" id="btn2" value="测试jq-bind" />
<input type="button" value="测试jq-one" name="" id="btn3"/>
</body>
</html>
还没有评论,来说两句吧...