【问题标题】:Why isn't clear button function isn't working?为什么不清除按钮功能不起作用?
【发布时间】:2021-11-06 03:12:07
【问题描述】:

清除按钮无法清除list-group history

//html 
<button class="btn btn-primary mb-3" 
   type="button" 
   id="clear-inputs"
   onclick="clearIt()">
    Clear history 
</button>
<form id="history"></form>
<div class="list-group" id="history"></div>
//javascript clear button function                           
function clearIt() {
  document.getElementById('history').value = "";
}

【问题讨论】:

  • 有两个 ID 为 history 的元素(无论如何它都是无效的,因为 ID 必须是唯一的)。然后你会得到第一个这样的元素,它是一个空的&lt;form&gt;,并且一个表单没有value。 (请注意,&lt;div&gt; 也没有 value,因此不清楚您在这里真正尝试做什么......)
  • 这能回答你的问题吗? Can an HTML element have multiple ids?

标签: javascript button


【解决方案1】:

您有两个具有相同id 的元素(&lt;form&gt;&lt;div&gt;)。浏览器会渲染它,但它是无效的 html,因为 id 属性应该对元素是唯一的。 getElementById() 将使用指定的id 获取第一个元素。

您的 html 的第二个问题是 formdiv 元素都没有 value 属性,因此您的函数无需清除任何内容。从您的示例中不清楚您的按钮应该清除哪个元素。对于&lt;div&gt;,您可以尝试设置document.getElementById('yourUniqueId').innerHtml = ""。这将清除 &lt;div&gt; 中的所有 html。

【讨论】:

    【解决方案2】:

    清除按钮不需要 javascript,您可以只在表单标签中使用 html 清除按钮。用于清除。

    这是一个简单的例子:example

    【讨论】:

      【解决方案3】:
      1. 您有两个“历史”ID - 不是一个好习惯

      2. 使用 'innerhtml' 而不是 value - 会产生更好的结果。 value 对于像

        这样的类似输入更好

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      【解决方案4】:

      确保为元素提供唯一 ID, 以上2个元素ID相同,调用前必须定义函数。

      • 始终检查您的控制台是否有日志记录/错误:)

      【讨论】:

        猜你喜欢
        • 2021-11-24
        • 1970-01-01
        • 2012-03-08
        • 2020-06-29
        • 2014-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多