猿问

切换复选框

     <form>


    Age: <input type="checkbox" class="first" value="Below 10">Below 10

      <input type="checkbox" class="first" value="Below 20"> Below 20

      <input type="checkbox" class="first" value="Below 30">Below 30

      <br>


      You have clicked: 

    <span id="maClass">

      

    </span>


    </form>

    <script type="text/javascript">

      var maClass = document.querySelector("#maClass");

      var first = document.querySelectorAll(".first");


      var isClicked = false;

      var i=0;

      for(i; i<first.length ; i++){


        first[i].addEventListener("click", function() {

  

        if(isClicked){

          maClass.style.display = "none";

          isClicked = false;

        }else{

          maClass.style.display = "inline";

          maClass.style.display = first[i].getAttribute("value");

          isClicked = true; 

          }


        });

        }

    </script>


我试图让这 3 个复选框切换。我在 Javascript 中使用了 eventListener。我对 3 个不同的复选框使用了相同的类名。这是因为,它将帮助我将整个决策存储到一个数组中。但它不起作用 我不能让它切换。请帮忙


湖上湖
浏览 117回答 1
1回答

九州编程

听起来您想要做的是更改<span id="maClass">单击复选框时的值。如果您不想同时选择所有单选按钮,您实际上应该使用它们。它可以有一个更简单的 JS 代码(例如,不需要保存isClicked或类似的东西)。这是更新后的代码:<body>&nbsp; <form>&nbsp; &nbsp; Age: <input type="radio" name="first" class="first" value="Below 10">Below 10&nbsp; &nbsp; &nbsp; &nbsp; <input type="radio" name="first" class="first" value="Below 20"> Below 20&nbsp; &nbsp; &nbsp; &nbsp; <input type="radio" name="first" class="first" value="Below 30">Below 30&nbsp; &nbsp; &nbsp; &nbsp; <br>&nbsp; &nbsp; &nbsp; &nbsp; You have clicked:&nbsp;&nbsp; &nbsp; <span id="maClass">&nbsp; &nbsp; </span>&nbsp; </form>&nbsp; <script type="text/javascript">&nbsp; &nbsp; &nbsp; &nbsp; var maClass = document.querySelector("#maClass");&nbsp; &nbsp; &nbsp; &nbsp; var first = document.querySelectorAll(".first");&nbsp; &nbsp; &nbsp; &nbsp; var i=0;&nbsp; &nbsp; &nbsp; &nbsp; for(i; i<first.length ; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; first[i].addEventListener("click", function(e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maClass.innerHTML = e.target.value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; </script></body>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答