Javascript检查未定义的问题

时间:2018-03-02 10:47:17

标签: javascript

以下代码在控制台中抛出一条错误消息,我不理解这个逻辑,因为在我的代码中你可以看到我已经编写了if语句,应首先检查对象是否存在。



if (typeof document.getElementById("trbrok0").checked != "undefined") document.getElementById("trbrok0").checked = false;
if (typeof document.getElementById("trbrok1").checked != "undefined") document.getElementById("trbrok1").checked = false;
if (typeof document.getElementById("trbrok2").checked != "undefined") document.getElementById("trbrok2").checked = false;
if (typeof document.getElementById("trbrok3").checked != "undefined") document.getElementById("trbrok3").checked = false;




就像你可以看到我们应该首先检查对象是否存在,然后尝试更改" check"的值。对象中的属性。 但我总是收到以下错误消息:

Uncaught TypeError: Cannot read property 'checked' of null

3 个答案:

答案 0 :(得分:5)

因为document.getElementById("trbrok0")返回一个DOM节点,如果它不存在,则返回nullnull没有属性checked,因此document.getElementById("trbrok0").checked会抛出错误。

修复方法是添加一个检查,如果该节点首先存在if(document.getElementById("trbrok0")!= null){ }

答案 1 :(得分:1)

  

看看



package net.codejava.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            // loads configuration and mappings
            Configuration configuration = new Configuration().configure();
            ServiceRegistry serviceRegistry
                = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();

            // builds a session factory from the service registry
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);           
        }

        return sessionFactory;
    }
}

function checkNullAndSetVal(id, val) {
  if (document.getElementById(id) == null) {
    console.log(id + ", Null or Undefined");
    return;
  }

  document.getElementById(id)["checked"] = val;
  console.log("Successfully Updated: ", id);
}

checkNullAndSetVal("trbrok0", false);
checkNullAndSetVal("trbrok1", true);
checkNullAndSetVal("trbrok2", false);
checkNullAndSetVal("trbrok3", true);




  

说明:

  1. 如果用双等于(==)检查null,则检查null和&未定义
  2. 使用函数减少重复代码。
  3. 使用方括号语法在对象中创建不存在的属性。例如obj [" newProperty"] ="一些价值&#34 ;;

答案 2 :(得分:0)

当您检查checked的类型时,document.getElementById选择的元素不存在,原因如下:

Cannot read property 'checked' of null

因为null没有名为checked的媒体资源。