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";
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM