在If语句条件Javascript / jQuery中嵌入For循环

时间:2015-08-13 17:15:14

标签: javascript jquery html css radio-button

在尝试确保在允许用户提交之前,我的测验(我正在制作的)中的每个问题的至少单选按钮被检查时,我在if语句条件中使用了for循环。这是代码:

HTML:

<form name="quizform">
            <div id="quizpart1">
                <h2>Title</h2>
                <br>
                <div id="notfinished1">
                </div>
                <br>
                    <!---Question 1: --->
                    <div class="row">
                        <div class="col-xs-8">
                            <label>1) Have you ever ...?</label>
                        </div>
                        <div class="col-xs-4">
                            <input type="radio" name="heartAttack?" value="true">Yes</input>
                            <br>
                            <input type="radio" name="heartAttack?" value="false">No</input>
                        </div>
                    </div> 

我创建表单的HTML与其他问题的上述格式非常相似。

使用Javascript:

//Variables
var quizpart1names = ["heartAttack?", "familyHeartDisease?", "congenitalHeartDisease?", "lungDisease?", "currentHeartThyroidDisease?"];

//If Loop With For as a Conditional
if (
        for (i=0; i < quizpart1names.length; i++){
            $('input[name=quizpart1names[i]]:checked').length > 0;
        }
    ){ //Used the jQuery Function :checked, and the logic behind the .length > 0 is that the "true" and "false" both have lengths > 0.
        $("#quizpart1").hide();
        //... The code goes on, but it works when there is no for loop in the conditional (when I was not checking if all the questions in the quiz I am making were answered.)

不幸的是,在firefox浏览器中,当我运行这个网页时,我写的任何javascript(包括这个例子)都不再有效。对这个问题的任何见解都会有所帮助。

1 个答案:

答案 0 :(得分:1)

您不能在表达式中使用语句(for)。

您可以使用grep方法过滤出条件为真的项目,然后检查剩余的项目数。

如果您想要满足任何条件:

if (
  $.grep(quizpart1names, function(q){
    return $("input[name='" + q + "']:checked").length > 0;
  }).length > 0
) {
  ...
}

如果您希望所有条件都成立:

if (
  $.grep(quizpart1names, function(q){
    return $("input[name='" + q + "']:checked").length > 0;
  }).length == quizpart1names.length
) {
  ...
}