我尝试运行第一次可以运行的代码,但第二次就无法运行,我不知道为什么? 我想以一种可以反复发送多条消息的方式
var message = document.querySelector('.container');
var btn = document.getElementById('btn');
var inpt = document.getElementById('txt');
function AddMessage() {
if (String(inpt.value) != '' && isNaN(inpt.value) == true) {
message.innerHTML += `<p>${inpt.value} </p>`;
inpt.value = '';
}
}
input {
outline: none;
}
<div class="container">
<input type="text" value="" id="txt">
<button id="btn" onclick="AddMessage()">send</button>
<p>whats your name ?</p>
</div>
最佳答案
与 .innerHTML
相关的问题
您正在分配给 .innerHTML
。这会导致重新创建该元素的后代(请参阅 innerHTML
"On setting..." ):
const oldReference = document.getElementById("element");
document.body.innerHTML += ""; // Assigning to innerHTML
const newReference = document.getElementById("element");
const isSameElement = oldReference === newReference;
console.log({ isSameElement });
<div id="element">
如您所见,旧引用 btn
和 inpt
不会是 DOM 中当前的元素。
旁注:解析.innerHTML
可能相当耗时,它与用户输入的使用是security issue .
Security considerations
特别是对于用户输入,您不应该使用 .innerHTML
,因为这是将脚本插入网页的简单方法:
document.body.addEventListener("click", evt => {
if (!evt.target.closest("button")) return;
const input = document.querySelector("input");
document.body.innerHTML += input.value;
});
pre{padding:2px 4px;border:1px solid;width:min-content}
<input><button>Insert</button>
<p>Try to input this:</p>
<pre><code><img src=""
onerror="console.log('any script here!')"></code></pre>
<p>Then look into your browser console.
.innerHTML
的替代品
如果要添加元素,可以使用 document.createElement()
, Element.append()
,和Node.textContent
:
const input = document.querySelector("input");
document.querySelector("button").addEventListener("click", evt => {
const p = document.createElement("p");
p.textContent = input.value;
document.body.append(p);
input.value = "";
const currentInput = document.querySelector("input");
console.log("Is same input?", input === currentInput);
});
<input><button>Insert</button>
<p>Also try adding some HTML, for example: <code><span>Test</span>
关于javascript - 为什么输入值不会更新?当我点击发送按钮时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72678561/