【问题标题】:Why my HTML and JavaScript button are not working together?为什么我的 HTML 和 JavaScript 按钮不能一起工作?
【发布时间】:2021-03-13 14:33:41
【问题描述】:

嘿,我是编码新手,我正在开发一个新的 chrome 应用程序。到目前为止,我正在尝试制作一个在您单击它时计数的按钮。由于某种原因,它不起作用。这是 HTML:

var button = document.getElementById("button"),
   count = 0;
   button.onclick = function() {
    count += 1;
    button.innerHTML = "Button: " + count;
  };
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1> This is a "Button" (I think) </h1>
    <p> (Or is it?) </p>
    <button id="button"> Button: 0 </button>
</body>
</html>
  

【问题讨论】:

  • 您应该首先通过定义var button = document.getElementById("button") 来获取对按钮元素的引用。然后您可以为按钮元素添加事件侦听器,但您的函数定义也是错误的
  • 实际上,如果我运行您的代码,它似乎可以工作。究竟是什么不工作?

标签: javascript html google-chrome google-chrome-app


【解决方案1】:

您必须等到 DOM 加载完毕。使用window.onload 事件:

window.onload = function() {
  var count = 0;
  const button = document.getElementById('button');
  button.onclick = function() {
    count += 1;
    button.innerHTML = "Button: " + count;
  };
};

编辑:我也刚刚注意到您没有在 HTML 中包含脚本。

【讨论】:

    【解决方案2】:

    您的计数中缺少一个变量类型。

    您想在实际操作之前确保您的按钮内部有某种文本 开始增加它。

    最后,您需要使用 "document.getElementById("id_goes_in_here") 从 html 中获取元素

    试试这个。

    document.getElementById("button").innerHTML = ` `; //Make sure to actually pull from your element in the html with this.
    
    let count = 0;
    button.innerHTML="Button " + count
    button.onclick = function() {
    count += 1;
    button.innerHTML = "Button: " + count;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-08
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      相关资源
      最近更新 更多