简体   繁体   English

textContent显示内容仅一会(使用addEventListener)

[英]textContent display Content only for a while (using addEventListener)

I'm trying to display typed text, but it shows only for a moment - don't know why. 我正在尝试显示键入的文本,但仅显示了一段时间-不知道为什么。

HTML 的HTML

<div>
  <h1 id="ASD"></h1>
</div>
<form>
  <input type="text" id="OUTPUT">
  <input type="submit" value="Check">
</form>

CSS 的CSS

div{
  height: 200px;
  width: 200px;
  background: red;
}

JS JS

let output= document.getElementById('OUTPUT');
const newSubmit = document.querySelector('input[type=submit]');

function checkNumber() {
  document.getElementById('ASD').textContent = output.value;
}
newSubmit.addEventListener('click', checkNumber, false);

http://codepen.io/Shalahmander/pen/QdKvgJ http://codepen.io/Shalahmander/pen/QdKvgJ

Typed text should be display in box after click Submit. 单击提交后,输入的文本应显示在框中。

The page is refreshing on the submit click (the form is processed). 该页面在提交单击时刷新(处理表单)。 You can handle event object and call .preventDefault to cancel the default behavior, like this: 您可以处理event对象并调用.preventDefault取消默认行为,如下所示:

let output= document.getElementById('OUTPUT');
const newSubmit = document.querySelector('input[type=submit]');

function checkNumber(e) {
  document.getElementById('ASD').textContent = output.value;
  e.preventDefault();
}
newSubmit.addEventListener('click', checkNumber, false);

But I suggest using <button/></button> or <input type="button"></input> if you want to perform another action (than submit your form). 但是,如果您要执行其他操作(而不是提交表单),建议使用<button/></button><input type="button"></input>

Also, remember to close your tags: <input>...</input> or <input /> . 另外,请记住关闭标签: <input>...</input><input />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM