在點擊函數里寫document.write,,怎么不像之前一樣在原有的網頁內容后面輸出呢
<!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" value="music">? 音樂
? ? ? ? ? <input type="checkbox" name="hobby" id="hobby2" value="music">? 登山
? ? ? ? ? <input type="checkbox" name="hobby" id="hobby3" value="music">? 游泳
? ? ? ? ? <input type="checkbox" name="hobby" id="hobby4" value="music">? 閱讀
? ? ? ? ? <input type="checkbox" name="hobby" id="hobby5" value="music">? 打球
? ? ? ? ? <input type="checkbox" name="hobby" id="hobby6" value="music">? 跑步 <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(i=0;i<hobby.length;i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if(hobby[i].type=="checkbox")
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? //document.write(hobby[i].value+"<br>");? ?//問題:在這里輸出內容會把之前的網頁都清了,只有一個value的值在這里
? ? ? ? ? ? ? ? ? ? hobby[i].checked=true;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? // 任務1?
? ? ? ? ? ?
? ? ? ? }
? ? ? ? function clearall(){
? ? ? ? ? ? var hobby = document.getElementsByName("hobby");
? ? ? ? ? ? ?for(i=0;i<hobby.length;i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if(hobby[i].type=="checkbox")
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? hobby[i].checked=false;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ?// 任務2? ??
? ? ? ? ? ??
? ? ? ? }
? ? ? ??
? ? ? ? function checkone(){
? ? ? ? ? ? var j=document.getElementById("wb").value;
? ? ? ? ? ? var j_id="hobby"+j;
? ? ? ? ? ? document.getElementById(j_id).checked=true;
? ? ? ? ?// 任務3
? ? ? ??
? ? ? ? }
? ? ? ??
? ? ? ? </script>
? ? </body>
</html>
2019-04-12
我的理解應該是document.getElementByTagName()返回的元素數組應該是由這些元素的地址組成的數組(所以可以直接通過對數組元素修改屬性作用到頁面元素本身上),而不是把元素重新賦值到一個新數組。
所以第一次document.write()時,因為在頁面成功加載成功后執行document.write()會把頁面原有內容清空,所以寫完第一個music,再循環時由hobby[i]地址返回的元素都是空的了,于是不能輸出其它選項的value。
以上是我自己的理解,可能會有不對的地方
2019-03-14
for循環