注册 登录
编程论坛 JavaScript论坛

大家好,我初学Javascript,这儿有一串代码,里面有一段看不懂,麻烦大家帮一下,先谢了

LIU61ZHU61ZH 发布于 2010-09-30 20:46, 602 次点击
程序代码:
<html>
<head>
<title>自定义对象示例</title>
<style type="text/css">
<!--
body {
    font-family: "宋体";
    line-height: 20px;
    text-align: center;
    background-color:#9acdcd;
}
table {
    font-size: 12px;
    text-align:center
}
.title {
    color: #FFFFFF;
    text-align: center;
    font-family: "宋体";
    font-size: 14px;
    line-height: 25px;
    font-weight: bold;
}
.blue {
    color: blue;
    font-size: 12px;
}
    #Text1
    {
        width: 203px;
    }
    #Button1
    {
        width: 62px;
    }
-->
</style>
</head>
<body>
<script type="text/javascript">
Computation=function(){};
Computation.prototype={
  Factorial:function(num)
  {
   var rs=1;
   for(i=1;i<=num;i++)
   {
    rs*=i;
   }
   return rs;
  },
   cubic:function(num)
   {
    var rs;
    rs=Math.pow(num,3);
    return rs;
   }

 }
function IsNum(num)
{
var reNum=/^\d*$/;
return(reNum.test(num));
}
function getResult(num)
{
   if(IsNum(num))
   {
    var chk= document.getElementsByName('operation');
    var op="";
    for(var i = 0; i< chk.length; i++)
    {
     if(chk[i].checked)
     {
      op=chk[i].value
     }
    }
    switch(op)
    {
    case "阶乘":
    res=Computation.prototype.Factorial(num);
    alert(num+"的阶乘为"+res);
    break;
    case "三次方":
    res=Computation.prototype.cubic(num);
    alert(num+"的三次方结果为"+res);
    break;
    }
    }
    else
    alert(num+"不是数值类型");
}

 </script>
    <table style="width:100%;">
        <tr>
            <td style="font-size: 18px">
                请输入操作数:<input id="Text1" type="text" /></td>
        </tr>
        <tr>
            <td>
                <input id="Radio1" name="operation" type="radio" value="阶乘" />阶乘
                <input id="Radio2" name="operation" type="radio" value="三次方" />三次方</td>
        </tr>
        <tr>
            <td>
                <input id="Button1" type="button" value="确定" onclick="getResult(Text1.value)"

/></td>
        </tr>
    </table>
</body>
</html>


问题:这段for语句是什么意思,在这段代码中启了什么作用啊

for(var i = 0; i< chk.length; i++)
    {
     if(chk[i].checked)
     {
      op=chk[i].value
     }
2 回复
#2
gameohyes2010-09-30 22:47
首先看第一句:(注意红色标识部分)
1.  <input id="Radio1" name="operation" type="radio" value="阶乘" />阶乘
                <input id="Radio2" name="operation" type="radio" value="三次方" />三次方</td>
2.var chk= document.getElementsByName('operation');//得到关于operation的对象数组
3.for(var i = 0; i< chk.length; i++)    //遍历数据
    {
     if(chk[i].checked)                //确认选择的哪个单选按钮(阶乘或三次方)
     {
      op=chk[i].value                  //得到当前选择的按钮的值
     }
4.  switch(op)    //根据op的值,进行处理
    {
    case "阶乘":
    res=Computation.prototype.Factorial(num);
    alert(num+"的阶乘为"+res);
    break;
    case "三次方":
    res=Computation.prototype.cubic(num);
    alert(num+"的三次方结果为"+res);
    break;
    }
#3
LIU61ZHU61ZH2010-10-02 14:16
恩,知道了,谢了
1