问题吗描述:今天在用js的面向对象时遇到这个错误,因此记录一下解决这个错误的方案。
HTML代码:
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
#btndiv{
width: 100px;
height: 100px;
background-color: forestgreen;
}
</style>
<body>
<input type="button" value="点检按钮改变颜色" id="btn"/>
<div id="btndiv"></div>
</body>
</html>
js代码:
<script>
function Changestyle(btn,btndiv,cr){
this.objectid=document.getElementById(btn)
this.objectdiv=document.getElementById(btndiv)
this.color=cr
}
var cs=new Changestyle('btn','btndiv','red')
Changestyle.prototype.init=function (){
var that=this
that.objectid.onclick=function(){
that.objectdiv.style.backgroundColor=that.color
}
}
console.log(cs)
cs.init()
</script>
解决方案:
1.使用window.οnlοad=function (){}方式,使用该方法会在浏览器渲染之后加载。
2.由于js代码的执行顺序是从上至下执行流程的,所以有可能js根本就没有获取到该元素,因此将js代码放到body里面。
3.第三种其实和第二种方式是一样的,检查一下设置点击事件的元素是否获取到了,如果没有获取到也会报这个错误。