如何处理getElementById返回Null

在我们的Web应用程序上有很多页面。 其中一些包含元素“Ribbon.ListForm.Display.Manage.Workflows-Medium”,而有些页面则没有。

我想使用相同的脚本来检查所有页面。 该脚本将隐藏元素“Ribbon.ListForm.Display.Manage”,“Ribbon.ListForm.Display.Manage.Workflows-Medium”和“Ribbon.ListForm.Display.Manage.CheckOut-Large”(如果有)。

function hideEdit() { var edit = document.getElementById("Ribbon.ListForm.Display.Manage"); if (typeof edit !== "undefined" && edit.value == ''){edit.style.display = "none";}; var wf = document.getElementById("Ribbon.ListForm.Display.Manage.Workflows-Medium"); if (typeof wf !== "undefined" && wf.value == ''){wf.style.display = "none";}; var checkout = document.getElementById("Ribbon.ListForm.Display.Manage.CheckOut-Large"); if (typeof checkout !== "undefined" && checkout.value == ''){checkout.style.display = "none";}; } 

问题是当页面不包含“Ribbon.ListForm.Display.Manage.Workflows-Medium”(第2个元素)但包含“Ribbon.ListForm.Display.Manage.CheckOut-Large”(第3个元素)时,脚本将停在中间,错误[object is null or undefined]。 因此,隐藏了第一个元素,但没有隐藏第三个元素。

你能建议如何修改我的脚本吗? 谢谢。

因为如果找不到元素, getElementById()将返回null。

element是对Element对象的引用,如果具有指定ID的元素不在文档中,则为null。

您可以检查truthy值而不是使用typeof测试

 if (edit && edit.value == ''){edit.style.display = "none";}; 

演示: 小提琴

您可以像这样检查null元素:

 if (edit!=null && edit.value == '') if (wf!=null && wf.value == '') if (checkout!=null && checkout.value == '') 

即使页面中不存在该元素,返回类型也将是对象,返回值将为null。 所以,你也可以检查空案例。 请参阅修改后的代码。

 function hideEdit() { var edit = document.getElementById("Ribbon.ListForm.Display.Manage"); if ( edit != null && typeof edit !== "undefined" && edit.value == ''){edit.style.display = "none";}; var wf = document.getElementById("Ribbon.ListForm.Display.Manage.Workflows-Medium"); if (wf != null && typeof wf !== "undefined" && wf.value == ''){wf.style.display = "none";} var checkout = document.getElementById("Ribbon.ListForm.Display.Manage.CheckOut-Large"); if (checkout != null && typeof checkout !== "undefined" && checkout.value == ''){checkout.style.display = "none";} 

}

谢谢,varun。

由于问题用jQuery标记:

 $('#Ribbon\.ListForm\.Display\.Manage,#Ribbon\.ListForm\.Display\.Manage\.Workflows-Medium,#Ribbon\.ListForm\.Display\.Manage\.CheckOut-Large') .filter(function() { return this.value == ''; }) .hide(); 

首先,它会选择你感兴趣的元素; 然后,它将隐藏那些与基于值的简单filter匹配的内容。