zoukankan      html  css  js  c++  java
  • 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";
        }
    }
  • 相关阅读:
    Day1-CSS-下拉菜单
    scau 1138 代码等式
    SCAU-1076 K尾相等数
    勾股数专题-SCAU-1079 三角形-18203 神奇的勾股数(原创)
    SCAU-1144 数星星-HDU-1166-树状数组的应用
    NodeJs Fs模块
    Node核心模块
    flutter环境配置
    纯CSS制作图形效果
    CSS3选择器
  • 原文地址:https://www.cnblogs.com/wangduojing/p/9809520.html
Copyright © 2011-2022 走看看