javascript - label标签绑定jQuery的click事件,但click事件会触发两次
本文介绍了javascript - label标签绑定jQuery的click事件,但click事件会触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
以下是我的代码,想实现点击单选项,获取得分的需求,但是点击单选项的文字,得分会被计算两次,请问我的代码出现了什么问题?谢谢
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<label class="man"><input type="radio" name="sex" id="man">man</label>
<label class="woman"><input type="radio" name="sex" id="woman">woman</label>
<script src="JS/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function(){
var score = 0;
$(".man").click(function(){
score = score + 1;
console.log(score);
// score = 0;
});
$(".woman").click(function(){
score = score + 2;
console.log(score);
// score = 0;
});
})
</script>
</body>
</html>
解决方案
我认为原因出在事件捕获。
先说解决方案:在你的代码里,为click
绑定的函数添加return false
:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<label class="man"><input type="radio" name="sex" id="man">man</label>
<label class="woman"><input type="radio" name="sex" id="woman">woman</label>
<script src="JS/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function(){
var score = 0;
$("#man").click(function(){
score = score + 1;
console.log(score);
// score = 0;
/*修改部分开始*/
return false;
/*修改部分结束*/
});
$("#woman").click(function(){
score = score + 2;
console.log(score);
// score = 0;
/*修改部分开始*/
return false;
/*修改部分结束*/
});
})
</script>
</body>
</html>
现在我们来验证一下猜测:假设是事件捕获,那么只需要在触发的时候弹出触发事件的对象即可。所以我们修改一下click
绑定的函数:
$("#man").click(function(event){
score = score + 1;
console.log(score);
// score = 0;
/*修改部分开始*/
console.log(event.target)
/*修改部分结束*/
});
看下结果:
//控制台打印的结果
1
<label class="man">…</label>
2
<input type="radio" name="sex" id="man">
问题已解决,就这么简单。
这篇关于javascript - label标签绑定jQuery的click事件,但click事件会触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文