日期:2014-05-16  浏览次数:20357 次

JS简单程序出错,求解。
<html>
<head>
<title>JS_text </title>
<script type="text/javascript">
function fun(){

var radio=document.getElementsByName("color")
if(radio.length==0){
alert("error");return;
}

for(var i=0;i<3;i++){ //此处为何只能循环一次?然后length=0.
document.write(radio[i].value+
" "+"lenght="+radio.length+" i="+i+"<br/>")
}
document.write(radio[2]);
}
function getV(){
var v1=document.getElementById("div");
v1.innerText="hello!";//这里也不对,输出不来。

}
</script>
</head>
<body onload="getV()">
<div id="div"> </div>
<form method="post" action='1.htm'>
<fieldset>
<legend>Choose the color you favourite</legend>
<input type="radio" name="color" value="red">red<br>
<input type="radio" name="color" value="blue"/>blue<br/>
<input type="radio" name="color" value="yellow"/>yellow<br/>
<input type="submit" name="submit" value="submit" onclick="fun()"/> 
</fieldset>
</form>
</body>
</html>

------解决方案--------------------
将document.write改成alert

你使用document.write,写完第一行,其他的东西已经统统不存在了。所以出错
------解决方案--------------------
.innerText,你要这样用也行。就你目前的结构,不会出错,我测试过了,输出无误
不过,操作类似于div之类的,你可以使用:innerHTML
------解决方案--------------------
var result = "";
 for(var i=0;i<3;i++){ //此处为何只能循环一次?然后length=0.
 result +=radio1[i].value+" "+"lenght="+radio1.length+" i="+i+"<br/>";
 }
 document.write(result);
 document.write(radio1[2]);

这样也可以~~
------解决方案--------------------
第一,for循环里面定义个变量,然后字符串加起来,for完了再document.write
第二个用innerHTML
------解决方案--------------------
document.write 每执行一次就重绘一次dom
------解决方案--------------------
探讨

第一,for循环里面定义个变量,然后字符串加起来,for完了再document.write
第二个用innerHTML

------解决方案--------------------
var radio=document.getElementsByName("color")
这是不是要写成getElementsByTagName("color")?有getElementsByName("color")这个方法吗?

------解决方案--------------------
同2楼,document.write()会把页面上的其他内容都覆盖住了 相当于重写了一下页面吧