在本节的任务3中,我输入
var j=document.getElementById("wb").value;var k=j+1;
var hobby = document.getElementById("hobby"+j);
hobby.checked=true;
是正确的,但是输入
var j=document.getElementById("wb").value;var k=j+1;
var hobby = document.getElementsByName("hobby");
hobby[j+1].checked=true;
所有按钮都没反应,而把hobby[j+1]改成hobby[j],按钮就会错位被勾选。为什么hobby【】中不能识别表达式呢?
因为var j=document.getElementById("wb").value返回值是字符串,所以不能+1
之前写的没错的,因为我用hobby[i]是会勾选按钮的,只不过错了一位,但是hobby[i+1]完全没反应。。
<html> <head> <script type="text/javascript"> function alertIndex() { var x=document.getElementById("mySelect").selectedIndex; var y=document.getElementsByTagName("option"); alert(y[x+1].text + " has the index of: " + y[x+1].index); } </script> </head> <body> <form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br /> <br /> <input type="button" onclick="alertIndex()" value="Show index of the chosen fruit"> </form> </body> </html> </body> </html>
这里y[x]和y[x+1]都可以,所以你检查一下是不是之前写的有错误