label标签绑定jQuery的click事件,但click事件会触发两次

以下是我的代码,想实现点击单选项,获取得分的需求,但是点击单选项的文字,得分会被计算两次,请问我的代码出现了什么问题?谢谢

<!DOCTYPE html>

<html>

<head>

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


达令说
浏览 1030回答 1
1回答

米琪卡哇伊

我认为原因出在事件捕获。先说解决方案:在你的代码里,为click绑定的函数添加return false:<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <title></title></head><body>&nbsp; <label class="man"><input type="radio" name="sex" id="man">man</label>&nbsp; <label class="woman"><input type="radio" name="sex" id="woman">woman</label>&nbsp; <script src="JS/jquery-3.1.1.min.js"></script>&nbsp; <script>&nbsp; &nbsp; $(document).ready(function(){&nbsp; &nbsp; &nbsp; var score = 0;&nbsp; &nbsp; &nbsp; $("#man").click(function(){&nbsp; &nbsp; &nbsp; &nbsp; score = score + 1;&nbsp; &nbsp; &nbsp; &nbsp; console.log(score);&nbsp; &nbsp; &nbsp; &nbsp; // score = 0;&nbsp; &nbsp; &nbsp; &nbsp; /*修改部分开始*/&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; /*修改部分结束*/&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; $("#woman").click(function(){&nbsp; &nbsp; &nbsp; &nbsp; score = score + 2;&nbsp; &nbsp; &nbsp; &nbsp; console.log(score);&nbsp; &nbsp; &nbsp; &nbsp; // score = 0;&nbsp; &nbsp; &nbsp; &nbsp; /*修改部分开始*/&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;/*修改部分结束*/&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; })&nbsp; </script></body></html>现在我们来验证一下猜测:假设是事件捕获,那么只需要在触发的时候弹出触发事件的对象即可。所以我们修改一下click绑定的函数:$("#man").click(function(event){&nbsp; &nbsp; score = score + 1;&nbsp; &nbsp; console.log(score);&nbsp; &nbsp; // score = 0;&nbsp; &nbsp; /*修改部分开始*/&nbsp; &nbsp; &nbsp; &nbsp;console.log(event.target)&nbsp; &nbsp; /*修改部分结束*/&nbsp; });看下结果://控制台打印的结果1<label class="man">…</label>2<input type="radio" name="sex" id="man">
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript