大家好,请告诉我为什么这段代码没有给出任何回复

时间:2013-03-19 06:05:13

标签: javascript

检查代码......

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
function operation(thevalue)
{
    var result;
    var one=document.forms["myform1"]["one"];
    var two=document.forms["myform1"]["two"];
    document.write(one);
    var x=document.getElementById(thevalue).value;

    if(x == "add")
    {
        result=one+two;
        alert ("Answer is : "+result);
    }

}
</script>
</head>
<body>
<form name="myform1">
Enter 1st no :<input type="text" name="one"  /><br/>
Enter 2nd no :<input type="text" name="two"  /><br/>
<input type="radio" id="add" name="operation" value="add" onclick="operation(this.value)" />Add
<input type="radio" id="sub" name="operation" value="sub" onclick="operation(this.value)" />Sub
<input type="radio" id="mul" name="operation" value="mul" onclick="operation(this.value)" />Mul
<input type="radio" id="div" name="operation" value="div" onclick="operation(this.value)" />Div

</form>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

您的函数和输入名称具有相同的名称 并且您需要从输入中提取get值(并将它们解析为数字)

http://jsfiddle.net/VfnYB/1/

<form name="myform1">
Enter 1st no :<input type="text" name="one"  /><br/>
Enter 2nd no :<input type="text" name="two"  /><br/>
<input type="radio" id="add" name="operation" value="add" onclick="op(this.value)" />Add
<input type="radio" id="sub" name="operation" value="sub" onclick="op(this.value)" />Sub
<input type="radio" id="mul" name="operation" value="mul" onclick="op(this.value)" />Mul
<input type="radio" id="div" name="operation" value="div" onclick="op(this.value)" />Div

</form>



window.op=function(val)
{
    var result;
    var one=parseInt(document.forms["myform1"]["one"].value);
    var two=parseInt(document.forms["myform1"]["two"].value);

    if(val == "add")
    {
        result=one+two;
        alert ("Answer is : "+result);
    }

}

答案 1 :(得分:0)

将操作更改为导致冲突的其他名称..

答案 2 :(得分:0)

1)将操作改为另一个名称,因为您已将单选按钮命名为“操作”

<input type="radio" id="add" name="operation" value="add" onclick="operation(this.value)" />Add

2)在您的代码中, .value 部分缺失,否则您将只获取元素而不是其值。

 var one=document.forms["myform1"]["one"].value;
 var two=document.forms["myform1"]["two"].value;