我试着第一次运行代码,但第二次就不行了,我不知道为什么?

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>

推荐答案

Issues with .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">

如您所见,旧的引用btninpt将不是DOM中当前的元素.

Sidenote:解析.innerHTML可能非常耗时,它与用户输入的结合使用是security issue.

安全注意事项

特别是对于用户输入,您不应该使用.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>&lt;img src=""
  onerror="console.log('any script here!')"></code></pre>

<p>Then look into your browser console.

Alternatives for .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>&lt;span>Test&lt;/span>

Javascript相关问答推荐

Spring boot JSON解析错误:意外字符错误

如何使用JavaScript将文本插入空div

在open shadow—root中匹配时,使用jQuery删除一个封闭的div类

在JS中拖放:检测文件

在执行异步导入之前判断模块是否已导入()

我创建了一个创建对象的函数,我希望从该函数创建的对象具有唯一的键.我怎么能做到这一点?

如何修复我的数据表,以使stateSave正常工作?

映射类型定义,其中值对应于键

在FAQ Accodion应用程序中使用React useState时出现问题

如何在我的Next.js项目中.blob()我的图像文件?

如何使用基于promise (非事件emits 器)的方法来传输数据?

如果一个字符串前面有点、空格或无字符串,后面有空格、连字符或无字符串,则匹配正则表达式

是否可以将异步调用与useState(UnctionName)一起使用

如何在每隔2分钟刷新OKTA令牌后停止页面刷新

我无法在Api Reaction本机上发出GET请求

bootstrap S JS赢得了REACT中的函数/加载

我如何才能让p5.js在不使用实例模式的情况下工作?

单击时同时 Select 和展开可访问的行

将数据添加到数据库时不输出

我在JS代码中收到超过最大调用堆栈大小的错误,但我找不到原因.有谁能帮我搬一下吗?