javascript检查对象存在

javascript check object exists

本文关键字:存在 对象 检查 javascript      更新时间:2023-09-26

我有下面的代码来检查对象是否存在,以列出项目。出于测试目的,我只有一个对象sub_total_0,但脚本保持循环,因为typeof无法确定sub_total_1是否未定义,并继续执行2,3,4,5,。。。

var i = 0;
while (typeof document.getElementById("sub_total_" + i) != "undefined") {
    var obj_sub_total = document.getElementById("sub_total_" + i);
    if (obj_sub_total != "undefined") {
        if (fr.order_method_id.value == 1) {
            obj_sub_total.style.visibility = "visible";
        } else {
            obj_sub_total.style.visibility = "hidden";
        }
    }
    i++;
} 

您有

typeof document.getElementById("sub_total_" + i) != "undefined"

if (obj_sub_total != "undefined") {

CCD_ 4返回CCD_ 5或HTML元素。这两个都不是字符串"undefined",并且每一个的类型都将是"object"。因此,你的条件没有意义。

相反,你要测试真实性。HTML元素将始终为true,而null将始终为false。

while (document.getElementById("sub_total_" + i)) {

if (obj_sub_total) {

您的检查不起作用,因为在getElementById的返回值上使用typeof将始终给您"object",因为如果找不到它,它将返回null,而typeof null就是"object"

只需直接检查返回值:如果有一个元素,它就是一个"truthy"值(当用作条件时,它强制为true);如果没有,则null是一个"伪"值(强制为false)。

因此:

while (document.getElementById("sub_total_" + i)) {

你也不需要查两次,这就是你目前正在做的;相反:

var obj_sub_total;
while ((obj_sub_total = document.getElementById("sub_total_" + i)) != null) {

(从技术上讲,你不需要!= null,但如果没有它,看起来有点像你意外地在想要==的地方使用了=。)


另一种选择是使用类和querySelectorAll:

var list = document.querySelectorAll(".sub_total");

然后循环,而i< list.length,例如:

var list = document.querySelectorAll(".sub_total");
for (i = 0; i < list.length; ++i) {
    var obj_sub_total = list[i];
    // ...
}

或者,即使在使用ids:时也可以这样做

var list = document.querySelectorAll("[id^=sub_total]");

getElementById()如果找不到元素,则返回null,并且null的类型是对象,这就是您的条件不起作用的原因。

您只需检查它是否是一个truthy值,由于while()循环验证了对象,因此不需要if条件

var i = 0,
    obj_sub_total;
while (obj_sub_total = document.getElementById("sub_total_" + i)) {
    console.log(obj_sub_total)
    if (fr.order_method_id.value == 1) {
        obj_sub_total.style.visibility = "visble";
    } else {
        obj_sub_total.style.visibility = "hidden";
    }
    i++;
}

演示:Fiddle