Uncaught TypeError: Cannot set property 'onclick' of null;
一句话“确保click事件的dom节点渲染先于JS执行!”解决。
自己写的一段原生JS的click事件,JS代码是写在首页的
<script type="text/javascript">
var all_features = document.getElementById("all_features");
var all_features_down = document.getElementById("all_features_down");
all_features.onclick=function () {
var price_content = document.getElementsByClassName("price_content");
for (var i = 0; i < price_content.length; i++) {
price_content[i].style.display = "none";
}
all_features.style.display = "none";
all_features_down.style.display = "block";
};
all_features_down.onclick=function () {
var price_content_down = document.getElementsByClassName("price_content");
for (var i = 0; i < price_content_down.length; i++) {
price_content_down[i].style.display = "block";
}
all_features.style.display = "block";
all_features_down.style.display = "none";
};
</script>
代码没什么看的,关键的是我点击的dom没有在首页,还木有渲染出来,所以报了以上错误(虽说是错误,但对用户是无感的,没有任何影响,用户点击到了那个页面,照样是可以正常操作的)。
不过程序员的洁癖(no error):
改成 了
function trigger_switch_up() {
var price_content = document.getElementsByClassName("price_content");
for (var i = 0; i < price_content.length; i++) {
price_content[i].style.display = "none";
}
all_features.style.display = "none";
all_features_down.style.display = "block";
};
function () trigger_switch_down{
var price_content_down = document.getElementsByClassName("price_content");
for (var i = 0; i < price_content_down.length; i++) {
price_content_down[i].style.display = "block";
}
all_features.style.display = "block";
all_features_down.style.display = "none";
};
<div onClick="trigger_switch_down()">Some Content</div>