請問我直接使用innerHTML為什么不能修改掉h3標(biāo)簽里面的內(nèi)容的
<!DOCTYPE?HTML> <html> <head> <meta?http-equiv="Content-Type"?content="text/html;?charset=utf-8"?/> <title>系好安全帶,準(zhǔn)備啟航</title> <script?type="text/javascript"> var?charater1?=?document.getElementById("div1"); function?showText(){ ????charater1.innerHTML?=?"hello?world"; ????document.write(charater1.innerHTML); } function?showDialog(){ ????confirm("準(zhǔn)備好了,啟航吧!"); } </script> </head> <body> ????<h3?id="div1">let?us?study?JS</h3> ????<form> ????????<input?type="button"?value="showText"?onclick=showText()> ????????<input?type="button"?value="showDialog"?onclick=showDialog()> ????</form> </body> </html>
我想把 h3 里面的內(nèi)容還為 hello world, 但是沒有成功。請問這么樣才可以替換?
2020-10-22
兩種解決方案:
var
?charater1?=?document.getElementById(
"div1"
);
這一句代碼移動showText()方法里把script標(biāo)簽放在body標(biāo)簽內(nèi)最下面
頁面加載默認(rèn)是從上往下讀的在js代碼部分那時候還沒有p這個標(biāo)簽,因此無法獲取該id,證實(shí):在源代碼內(nèi)showText()方法內(nèi)添加alert(
charater1
),在頁面點(diǎn)擊showText按鈕,會看到charater1的值是null一般建議script標(biāo)簽放在body標(biāo)簽內(nèi)最下面
以上是個人理解,如有誤請?jiān)?br />
2020-11-14
1、2均可解決問題