【问题标题】:HTML button wont run functionHTML按钮不会运行功能
【发布时间】:2018-03-23 03:52:05
【问题描述】:

我对 javascript 和 html 完全陌生,我的 hello world 脚本无法正常工作。我想要一个按钮来触发警报。代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>hello world</title>
</head>
<body>
    <button type="button" onclick="click()">
        click me
    </button>   
    <script>
        function click(){
            alert("hello world");
        }
    </script>
</body>
</html>

【问题讨论】:

标签: javascript html button onclick alert


【解决方案1】:

这个可行,像“点击”这样的名字可能不应该用作在 html 中调用的函数名

<!DOCTYPE html>
<html>
<head>
    <title>hello world</title>
</head>
<body>
    <button type="button" onclick="someClick()">
        click me
    </button>   
    <script>
        function someClick(){
            alert("hello world");
        }
    </script>
</body>
</html>

【讨论】:

    【解决方案2】:

    使用内联事件处理程序是一种不好的做法,会导致代码分解不良、难以管理。认真考虑使用 JavaScript 附加您的事件,例如:https://developer.mozilla.org/en/DOM/element.addEventListener

    尝试附加一个事件侦听器,如下所示:

    document.querySelector('button').addEventListener('click', function() {
      alert("hello world");
    });
    <button type="button">
        click me
    </button>   

    【讨论】:

      【解决方案3】:

      它不起作用,因为点击词是javascript的保留词 提这个

      <!DOCTYPE html>
      <html>
      <head>
      <title>hello world</title>
      </head>
      <body>
      <button type="button" onclick="oneclick()">
          click me
      </button>   
      <script>
          function oneclick(){
              alert("hello world");
          }
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多