This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?

(6个答案)


3年前关闭。




我正在创建一个HTML页面,该页面是使用 bootstrap 构建的。这是最终的HTML代码和hello.js文件的代码:

document.getElementById("subm").onclick = function () {
  alert("Hello WOrld");
}
<!DOCTYPE html>
<html>
<head>
  <title>Calculator</title>
  <link rel="stylesheet" href="/stylesheets/style.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
</html>
<body>
  <link rel="stylesheet" href="/stylesheets/bootstrap.min.css">
  <script src="http://code.jquery.com/jquery.js"></script>
  <script src="javascripts/bootstrap.min.js"></script>
  <script src="javascripts/hello.js"></script>
  <h1>Calculator</h1>
  <form class="form-horizontal center1">
    <div class="control-group">
      <label for="num1" class="control-label">Number1</label>
      <div class="controls">
        <input id="num1" type="number" placeholder="Enter an Integer">
      </div>
    </div>
    <div class="control-group">
      <label for="num2" class="control-label">Number2</label>
      <div class="controls">
        <input id="num2" type="number" placeholder="Enter an Integer">
      </div>
      <div class="control-group">
        <label for="options" class="control-label">Options</label>
        <div class="controls"><br>
          <select id="options">
            <option value="+">+</option>
            <option value="-">-</option>
            <option value="*">*</option>
            <option value="/">/</option>
          </select>
        </div>
      </div>
      <div class="control-group">
        <div class="controls"><br>
          <button id="subm" type="submit" class="btn">Calculate</button>
        </div>
      </div>
      <div class="control-group">
        <div class="controls">
          <input id="cal" type="text" placeholder="Calculator output" disabled="true">
        </div>
      </div>
    </div>
  </form>
</body>


当我使用提交单击按钮时,而不是警报,我得到了错误



谁能告诉我为什么我要面对这个错误?帮助解决它。

最佳答案

问题似乎是您在加载元素之前正在执行脚本。

我假设此脚本已添加到hello.js文件中,该文件是在创建DOM之前添加的。

解决方案是在DOM准备就绪后执行脚本,如下所示:

window.onload = function(){
    document.getElementById("subm").onclick=function(){
        alert("Hello WOrld");
    }
}

所有处理DOM元素的JavaScript代码(例如上述代码)都必须在DOM加载后执行。

演示:Fiddle

关于javascript - 未捕获的TypeError : Cannot set property 'onclick' of null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17080502/

10-12 12:54
查看更多