【问题标题】:Clearing input field in JavaScript after click event单击事件后清除JavaScript中的输入字段
【发布时间】:2018-02-11 17:42:34
【问题描述】:

我用 JavaScript 制作了一个简单的列表项页面。一切都按预期工作。我想要的是,每次我添加一个新的列表项时,都应该清除输入字段。如中值应删除。

function addItem() {

  if (document.querySelector('.text-input').value) {

    const listItem = document.createElement('li');
    listItem.className = 'list-item'
    var input = document.querySelector('.text-input').value;
    listItem.textContent = input;
    document.querySelector('.list').appendChild(listItem);
    document.querySelector('.text-input').value = '';


  }

}

document.getElementById('btn').addEventListener('click', addItem);

实际上,我通过 addItem 回调函数中的最后一行代码实现了我想要的。但是,如果我写input = '';,而不是写document.querySelector('.text-input').value = '';,它就行不通了。这对我来说没有任何意义,因为我在该函数中声明了该变量并将其用于listItem.textContent = input;如你看到的。

【问题讨论】:

  • 因为这个var input = document.querySelector('.text-input').value 是一个用值初始化的变量声明。这样做input = '' 只是重新分配另一个值。可能您对引用属性value 感到困惑。
  • 请开始以声明变量的方式编写代码。不要使用这种“直接”的编码方式,因为维护和调试会出现很多错误。

标签: javascript dom input


【解决方案1】:

因为这个var input = document.querySelector('.text-input').value 是一个用值初始化的变量声明。这样做input = '' 只是重新分配另一个值。您对引用属性 value 感到困惑。

您可能想要做的是:

const listItem = document.createElement('li');
listItem.className = 'list-item'

var input = document.querySelector('.text-input'); // Get a reference of element text-input

listItem.textContent = input.value; //Use the current value of text-input.
document.querySelector('.list').appendChild(listItem); 

input.value = ''; // Modify the value of the text-input's reference.

【讨论】:

  • @MagneticKode 完全是 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多