以下代码在控制台中抛出一条错误消息,我不理解这个逻辑,因为在我的代码中你可以看到我已经编写了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
答案 0 :(得分:5)
因为document.getElementById("trbrok0")
返回一个DOM节点,如果它不存在,则返回null
。 null
没有属性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);

说明:
答案 2 :(得分:0)
当您检查checked
的类型时,document.getElementById
选择的元素不存在,原因如下:
Cannot read property 'checked' of null
因为null
没有名为checked
的媒体资源。