未捕获TypeError:无法将属性“onclick”设置为null [英] Uncaught TypeError: Cannot set property 'onclick' of null
问题描述
我在创建一个使用bootstrap构建的html页面是最终的html代码
i am creating a html page which is build using bootstrap here is the final html code
<!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文件的代码是
code of hello.js file is
document.getElementById("subm").onclick=function(){
alert("Hello WOrld");
}
当我点击按钮使用subm然后代替alert我收到错误
Uncaught TypeError:不能设置属性'onclick'为空
when i click on the button using subm then instead of alert i am getting error Uncaught TypeError: Cannot set property 'onclick' of null
可以任何一个请告诉我为什么面对这个错误?帮助解决它。
can any one please tell why i am facing this error?? help to resolve it.
推荐答案
问题似乎是您在元素加载之前执行脚本。
The problems seems to be you are executing the script before the element is loaded.
我假设这个脚本添加在创建dom之前添加的 hello.js
文件中。
I assume this script is added in the hello.js
file which is added before the dom is created.
这里的解决方案是在dom准备好之后执行脚本,如
The solution here is to execute the script after the dom is ready like
window.onload = function(){
document.getElementById("subm").onclick=function(){
alert("Hello WOrld");
}
}
演示:小提琴
这篇关于未捕获TypeError:无法将属性“onclick”设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!