【问题标题】:I want to make a clearable search field. Where did I make a mistake?我想制作一个清晰的搜索字段。我在哪里做错了?
【发布时间】:2019-06-15 14:48:24
【问题描述】:

我想创建一个清晰的搜索字段。当我点击十字按钮时,我想重置输入的值

function clear() {
  var a = document.getElementById('searchField');
  a.value = "";
}
<div class="searchGroup">
  <input type="text" id="searchField">
  <button onclick="clear()">&times;</button>
</div>

我希望输入应该重置为没有值。

【问题讨论】:

标签: javascript html


【解决方案1】:

将函数名称从 clear 更改为其他名称。虽然已弃用,但它可能会调用 document.clear

function clearInput() {
  document.getElementById('searchField').value = "";
}
<div class="searchGroup">
  <input type="text" id="searchField">
  <button type="button" onclick="clearInput()">&times;</button>
</div>

【讨论】:

    【解决方案2】:

    通过使用事件侦听器而不是内联 javascript 来使用正确的代码,比更改方法的名称更好。

    document.getElementById('clearSearch').addEventListener('click', clear);
    
    function clear() {
      document.getElementById('searchField').value = '';
    }
    <div class="searchGroup">
      <input type="text" id="searchField">
      <button type="button" id="clearSearch">&times;</button>
    </div>

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2015-03-21
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      相关资源
      最近更新 更多