简体   繁体   English

如何在js中检查多个class名称

[英]how to check more than one class name in js

<script src="https://code.jquery.com/jquery-1.12.4.min.js">
      var answers = ["A","C","B"], 
        tot = answers.length;
    function getScore(){
      var score = 0;
      for (var i=0; i<tot; i++)
        if($("input[class='question0']:checked").val()===answers[i])    //TODO add another classes like question1,question2,etc..

         score += 1; // increment only
      return score;
    }
    
    function returnScore(){
     
      $('p').html('Score: ' + getScore()  + '');
    }
    </script>

here in this line,在这一行,

if($("input[class='question0']:checked").val()===answers[i]) //TODO add another classes like question1,question2,etc..

how to check for more than one classes?如何检查多个课程? question+i is possible?问题+我是可能的? or how to mention many classes?或者如何提及许多课程? thanks in advance senior!先谢谢前辈!

You can just format i into your string like so:您可以像这样将i格式化为您的字符串:

for(let i = 0; i < tot; i++) {
   if($(`input[class='question${i}']:checked`).val() === answers[i])
      score++;
}

In general you can use string literals like so using the backtick character `:通常,您可以使用反引号字符 ` 来使用字符串文字:

 let variable = "value"; console.log(`A sentence containing a ${variable}`);

This is the way to select multiple classes in JQuery这是 JQuery 中的 select 多个类的方法

$("input[class*=question]")

Try the full code尝试完整代码

 var answers = ["A", "C", "B", "D"]; var inputList = $("input[class*=question]"); inputList.change(returnScore); function getScore() { var score = 0; inputList.each(function (i) { if ($(this).val() === answers[i] && $(this).is(":checked")) score += 1; }); return score; } function returnScore() { $("p").html("Score: " + getScore() + ""); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <div>answers = ["A", "C", "B", "D"]</div> <div> <input class="question0" type="checkbox" id="question0" value="A"/> <label for="question0">This is Question 0, value: A</label> </div> <div> <input class="question1" type="checkbox" id="question1" value="C"/> <label for="question1">This is Question 1, value: B</label> </div> <div> <input class="question3" type="checkbox" id="question3" value="R"/> <label for="question3">This is Question 3, value: R</label> </div> <div> <input class="question4" type="checkbox" id="question4" value="F"/> <label for="question4">This is Question 4, value: F</label> </div> <p></p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM