有人可以解释一段Javascript代码吗?

时间:2014-03-08 15:56:07

标签: javascript

我正在学校做一个项目,作为其中的一部分,我必须在我的html表单中包含单选按钮。下面是我不太了解的一些部分的Javascript代码。代码工作正常。有人可以给我一个代码如何工作的解释。

var check = false; 
for (var i=0; i < document.ExamEntry.Level.length; i++)
   {
   if (document.ExamEntry.Level[i].checked)
      {
      var radiovalue = document.ExamEntry.Level[i].value;
      check =true; 
      var usermessage=confirm("You have chosen: ".concat(radiovalue));

          if(usermessage == false)
              {
                 var radiovalue = "";
                check = false;
              }
      }
   }
<!--I understand the code below, its just some parts of the above code.
if (check ==false)
       {
       msg+="ERROR:You must select an entry level \n";  
       document.getElementById ('Levelcell'). style.color = "red";
       result = false;
       }

2 个答案:

答案 0 :(得分:1)

我添加了评论来帮助解释这个:

var check = false; 

// set a variable 'i' from 0 up to the ExamEntry level length (so for each radio)
// if there are 10 items, this code will run 10 times, each time with 'i' a different value from 0 to 9
for (var i=0; i < document.ExamEntry.Level.length; i++)
   {

   // is the radio button checked? If so, do the stuff inside. If not, skip this part
   if (document.ExamEntry.Level[i].checked)
      {

      // set variable radiovalue to the value of the particular radio button
      var radiovalue = document.ExamEntry.Level[i].value;

      // set the check variable to true
      check =true; 

      // ask the user to confirm the value and set usermessage based on confirmation
      var usermessage=confirm("You have chosen: ".concat(radiovalue));

        // if the user hits no on confirm, it will reset the radiomessage to blank and check to false
        if(usermessage == false)
          {
             var radiovalue = "";
             check = false;
          }
      }
   }

答案 1 :(得分:0)

所有表单元素都绑定到全局HTML文档变量。因此,页面上的某个位置必须有一个名称为ExamEntry的表单:

<form name='ExamEntry' id='ExamEntry` ...

下一部分是指表单中的元素。由于他们期待一个单选按钮,Level必须是无线电类型的输入:

<label name="Level" id="1" type="radio" ....
<label name="Level" id="2" type="radio" ....

循环遍历所有单选按钮。如果选中该按钮,它将获取检查的值,并显示该消息。如果找不到选中的按钮,则会显示错误消息。

相关问题