简单但易错的onclick-报错

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值