Cannot set property 'onclick' of null报错

经常几个页面使用公共js文件, 原来遇到也没留意, 原来是本页面执行的时候, 其他页面也在执行并赋予id于onclick.

因为页面是正常情况下是不存在null和undefined

if(null){
    console.log(1);
} else {
    console.log(2);
}//输出2
if(undefined){
    console.log(3);
} else {
    console.log(4);
}//输出4

所以解决的方法:

①最常用的方法, js写带有函数名的函数a, 在页面标签里使用时间<div onclick="a()"></div>

②每个点击页面之前写上判断,判断是否存在,如下

var tan = document.getElementById("tan");
var argeeSure = document.getElementById("argeeSure");
var close = document.getElementById("off");
var sure = document.getElementById("sure");
var body = document.getElementsByTagName("body")[0];
// console.log(body)

if(argeeSure)
argeeSure.onclick = function () {
    tan.style.display = "block";
    body.style.height = "100%";
    body.style.overflow = "hidden";
}
if(close)
close.onclick = function () {
    tan.style.display = "none";
    body.style.height = "auto";
    body.style.overflow = "auto";
}
if(sure)
sure.onclick = function () {
    tan.style.display = "none";
    body.style.height = "auto";
    body.style.overflow = "auto";
}

其中if(argeeSure)是简写形式, 只作用其简写下面两行, 相当于

if(argeeSure !=null && argeeSure != undefined){
    argeeSure.onclick = function () {
        tan.style.display = "block";
        body.style.height = "100%";
        body.style.overflow = "hidden";
    }
}

猜你喜欢

转载自www.cnblogs.com/wangduojing/p/9809520.html