為什么for循環(huán)在函數(shù)里不起作用?
<!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<hobby.length;i++){
???????????????document.write(hobby[i].type+"<br/>");
?????????????}
????????}
????????</script>
????</body>
</html>點(diǎn)擊全選checkall()后,只輸出一個(gè)checkbox。我把for循環(huán)放到函數(shù)外,就會輸出所有的type?
2016-11-12
因?yàn)槿绻皇亲詣?dòng)運(yùn)行,文檔流結(jié)束,當(dāng)點(diǎn)擊時(shí),document.write會清除當(dāng)前頁面所有內(nèi)容,然后for循環(huán)中第一次能獲取input,輸出document,第二次for循環(huán)頁面已經(jīng)一篇空白除了剛才輸出的內(nèi)容,因此獲取不到input,自然無法繼續(xù)循環(huán)輸出
2016-11-03
關(guān)注一下
2016-11-03
應(yīng)該是hobby[i].nodeType
還有這里用getElementsByName("hobby")比較好,這樣就能獲取所有的復(fù)選框了