hobby[parseInt(j)-1].checked=true; 求問解釋
<!DOCTYPE HTML>
<html>
??? <head>
??????? <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
??????? <title>無標(biāo)題文檔</title>
??? </head>
?? ?
??? <body>
??????? <form>
????????? 請選擇你愛好:<br>
????????? <input type="checkbox" name="hobby" id="hobby1">? 音樂
????????? <input type="checkbox" name="hobby" id="hobby2">? 登山
????????? <input type="checkbox" name="hobby" id="hobby3">? 游泳
????????? <input type="checkbox" name="hobby" id="hobby4">? 閱讀
????????? <input type="checkbox" name="hobby" id="hobby5">? 打球
????????? <input type="checkbox" name="hobby" id="hobby6">? 跑步 <br>
????????? <input type="button" value = "全選" onclick = "checkall();">
????????? <input type="button" value = "全不選" onclick = "clearall();">
????????? <p>請輸入您要選擇愛好的序號,序號為1-6:</p>
????????? <input id="wb" name="wb" type="text" >
????????? <input name="ok" type="button" value="確定" onclick = "checkone();">
??????? </form>
??????? <script type="text/javascript">
??????? function checkall(){
??????????? var hobby = document.getElementsByTagName("input");
?????????? for(var i=0;i<bobby.length;i++){
?????????????? hobby[i].checked=true;
?????????? }
??????? }
????? ?
??????? function clearall(){
??????????? var hobby = document.getElementsByName("hobby");
?????????? ?
???????? for(var i=0;i<hobby.length;i++){
???????????? hobby[i].checked=false;
???????? }// 任務(wù)2?????? ?
??????? }
?????? ?
??????? function checkone(){
??????????? var j=document.getElementById("wb").value;
?????? ?
???????? for(var i=0;i<hobby.length;i++)// 任務(wù)3
????????? if(parseInt(j) > 6 || parseInt(j)? < 1? ){
??????????????????? alert("不在此范圍內(nèi),請重新輸入!")
??????????????????? // document.write(j);
??????????????? }
??????????? }
??????????? var hobby = document.getElementsByName("hobby");??? ?
??????????? hobby[parseInt(j)-1].checked=true;
??????? }
?????? ?
??????? </script>
??? </body>
</html>
加粗部分的parseInt(j)-1 應(yīng)該怎么解釋?
為啥要用parseInt這個(gè)函數(shù)??????????????????????????????? 感激不盡·····
2016-08-23
應(yīng)該是防止出現(xiàn)小數(shù)吧,要是輸個(gè)3.3咋辦,用parseInt(j)轉(zhuǎn)成整數(shù)了,就安全唄,
hobby[parseInt(j)-1樓上樓上也說了,就是因?yàn)閿?shù)組的下標(biāo)是從0開始的,但我們看復(fù)選框是從1開始數(shù)的,即我們看到的第一個(gè)復(fù)選框 對應(yīng) 數(shù)組里面下標(biāo)為0的內(nèi)容
2016-08-19
parseInt() 函數(shù)可解析一個(gè)字符串,并返回一個(gè)整數(shù)。
2016-08-15
很容易理解,你輸入的是1-6對應(yīng)數(shù)組0-5,當(dāng)然要減一
其實(shí)可以不用parseInt也可以,因?yàn)闀詣愚D(zhuǎn)換格式。當(dāng)然用了從邏輯上更加說得過去,因?yàn)閖得到的是個(gè)字符型的,要把它變?yōu)檎筒趴梢宰鲞\(yùn)算,當(dāng)然做減法時(shí)會自動轉(zhuǎn)為整型(加法不行)