需要帮助以使Hello World App正常工作

时间:2019-05-26 21:19:53

标签: javascript html

我试图找出如何在单独的文件中使javascript与html一起使用的方法,以便我可以按照本教程https://www.w3schools.com/howto/howto_css_modals.asp进行操作,但我无法弹出警告。

这是我的代码。

到目前为止,我只能获得一个不执行任何操作的按钮。

var hellobutton = document.getElementById("hello");
hellobutton.onclick = function() {
alert("Hello World")
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="/static/main.css">
    <script type="text/javascript" src="/static/main.js"></script>
    <title>Title</title>
</head>
<body>
<div class="content-section">
<h1>Page</h1>
    <input type = "button" id="hello" value = "Say Hello" />
</div>
</body>
</html>

代码在这里有效,但在我的计算机上不可用。

1 个答案:

答案 0 :(得分:1)

它在第2行引发错误,因为它找不到符合该条件的任何元素,因此在第1行返回null。值null为“ nothing”,因此您无法将onclick事件设置为“没有”。 解决此问题的一种方法是在html元素加载后加载js(无需编辑js文件):

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="/static/main.css">
  <title>Title</title>
 </head>
 <body>
  <div class="content-section">
  <h1>Page</h1>
  <input type = "button" id="hello" value = "Say Hello" />
  </div>
  <script type="text/javascript" src="/static/main.js"></script>
 </body>
</html>

或者也可以仅在加载文档时调用js代码(无需编辑html文件):

document.addEventListener('DOMContentLoaded', function() {
   var hellobutton = document.getElementById("hello");
   hellobutton.onclick = function() {
          alert("Hello World")
   }
}, false);

我找到了此代码here

相关问题