為什么for循環在函數里不起作用?
<!DOCTYPE?HTML> <html> ????<head> ????????<meta?http-equiv="Content-Type"?content="text/html;?charset=gb2312"> ????????<title>無標題文檔</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>
點擊全選checkall()后,只輸出一個checkbox。我把for循環放到函數外,就會輸出所有的type?
2016-11-12
因為如果不是自動運行,文檔流結束,當點擊時,document.write會清除當前頁面所有內容,然后for循環中第一次能獲取input,輸出document,第二次for循環頁面已經一篇空白除了剛才輸出的內容,因此獲取不到input,自然無法繼續循環輸出
2016-11-03
關注一下
2016-11-03
應該是hobby[i].nodeType
還有這里用getElementsByName("hobby")比較好,這樣就能獲取所有的復選框了