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>
阅读 10k
2 个回答

我认为原因出在事件捕获
先说解决方案:在你的代码里,为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">​

问题已解决,就这么简单。

为什么 不绑定到 input 上:

<!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>

如果坚持要绑定到 label 上,因为他就是这样设定了label标签,神也救不了你了。

为了让你更快入坑,推你一把:
图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题