首页 > 解决方案 > 如何让我的 HTML 按钮调用我的 Javascript?

问题描述

所以我一直在研究如何解决这个问题,但没有任何效果。我的问题是我试图在 HTML 中创建一个按钮并使用它在我的 javascript 中调用我的函数,但每次我遇到错误或什么都没有发生。

这是我一直在尝试的代码

HTML:

      <script type="text/javascript" src="script.js">



      </script>
      <button onclick= "test1"> test</button>
    </html>

Javascript:

    onEvent("test1", "click", function( ) {
      console.log("message");
    });


    console.log ("test");

标签: javascripthtmlbutton

解决方案


您可以将 onclick 属性与函数一起使用:

function test1() {
  console.log('message');
}
<button onclick= "test1()"> test</button>

或者动态添加事件监听器:

var button = document.getElementById('button');
button.addEventListener('click', function () {
console.log('message');
});
<button id="button"> test</button>


推荐阅读