onClick在非内联javascript中不起作用

onClick在非内联javascript中不起作用,javascript,html,Javascript,Html,因此,我正在关注来自firefox()的javascript演示,我实际上复制并粘贴了网站上的最后一个演示 index.html: <html> <head> <h1>Hello there</h1> </head> <body> <button>Change user</button> <script src = "app.js"></script> </

因此,我正在关注来自firefox()的javascript演示,我实际上复制并粘贴了网站上的最后一个演示

index.html:

<html>
<head>

    <h1>Hello there</h1>

</head>
<body>
<button>Change user</button>
<script src = "app.js"></script>

</body>
</html>

我点击了网页上的按钮,但什么也没发生。。。有什么建议吗?

我怀疑这是因为您选择了JavaScript元素,因此按钮事件绑定是在加载DOM之前执行的

您可以使用:

document.addEventListener("DOMContentLoaded", function(event) { 
  // add all the JS here so that the DOM is loaded when you 
  // run your selector.
});

或者,如果您要使用jQuery,您可以使用
$(document).ready()
函数

您的
h1
标题位于文档的
标题中,该标题在页面上不可见。将其移动到
主体中
。确实如此!非常感谢你!
document.addEventListener("DOMContentLoaded", function(event) { 
  // add all the JS here so that the DOM is loaded when you 
  // run your selector.
});