jQuery绑定事件
程序员文章站
2022-05-31 11:53:38
...
bind():对匹配的元素绑定事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<input type="button" value="按钮"/>
<script>
$("[type='button']").bind("click",function(){
console.log("按钮");
})
</script>
</body>
</html>
unbind():删除已绑定的制定事件,若无参数,删除全部事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<input type="button" value="按钮"/>
<script>
$("[type='button']").bind("click",function(){
console.log("按钮");
})
$("[type='button']").unbind("click");
</script>
</body>
</html>
one():触发一次即删除事件
<input type="button" value="按钮"/>
<script>
$("input").one("click",function(){
console.log(1111);
})
</script>
只能执行一次
submit()、trigger()、keydown():按下enter键触发
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<form id="id" action="http://www.baidu.com">
<input type="hidden" value="按钮"/>
</form>
<script>
$(window).keydown(function(){
if(event.keyCode==13){
$("#id").submit();
//$("#id").trigger("submit");
}
})
</script>
</body>
</html>
click():点击触发
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<form id="search" action="https://www.baidu.com/s">
<input type="button" id="search_btn" value="百度一下" />
</form>
<script>
$("#search_btn").click(function(){
$("#search").submit();
})
</script>
</body>
</html>
change():内容改变触发
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<form>
<input id="id"/>
</form>
<script>
$("#id").change(function(){
console.log("点击");
})
</script>
</body>
</html>
事件冒泡:事件处理函数中返回false会对事件停止冒泡,还可以停止元素的默认行为,就像form表单的onsubmit(“return f()”)返回false就无法提交一样
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<!--超链接失效,点击无法跳转-->
<a href="http://www.baidu.com" onclick="return test();">百度</a>
<script>
function test(){
console.log("点击了...");
return false;
}
</script>
</body>
</html>