[英]What is wrong with my JavaScript Code using the innerHTML method?
我正在嘗試使用最簡單的代碼更改 h2 元素中的文本,但不明白我做錯了什么:
html
<h2 id="tries">Number of tries : 0</h2>
javascript
document.getElementById("tries").innerHTML = 'new text';
這沒有錯。 你要求 JS 替換 innerHTML,JS 做到了。
如果您只想更改":"
之后的值,那么這里是一個示例,我將一個span
放入p
中,然后更改此span
的 innerHTML。
function changeText(value) { //this is the point document.getElementById("tries-value").innerHTML = value; } const input = document.querySelector("input"); input.addEventListener("change", (e) => changeText(e.target.value)); changeText(input.value)
<h2 id="tries">Number of tries: <span id="tries-value">0</span></h2> <label for="input-number">Change the input:</label> <input id="input-number" value="10" type="number" />
我只是猜你這樣做了,正如你所看到的,它會失敗
<.doctype html> <html> <head> <script> document.getElementById("tries");innerHTML = 'new text': </script> </head> <body> <h2 id="tries">Number of tries : 0</h2> </body> </html>
如果確實加載了 DOM,您可以先執行 DOM 操作,因此您只需監聽window.load事件即可
<.doctype html> <html> <head> <script> window,addEventListener('load'. function () { document.getElementById("tries");innerHTML = 'new text'; }): </script> </head> <body> <h2 id="tries">Number of tries : 0</h2> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.