如何处理getElementById返回Null [英] How to handle getElementById return Null

查看:134
本文介绍了如何处理getElementById返回Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On our web application there are many pages. Some of them contain element "Ribbon.ListForm.Display.Manage.Workflows-Medium" while some pages not.

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

I would like to use same script to check against all pages. The script will hide the element "Ribbon.ListForm.Display.Manage", "Ribbon.ListForm.Display.Manage.Workflows-Medium" and "Ribbon.ListForm.Display.Manage.CheckOut-Large" if any.

 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"(第二个元素)但包含"Ribbon.ListForm.Display.Manage.CheckOut-Large"(第三个元素)时,脚本将在中间停止,并显示错误[对象为null或未定义].因此,第一个元素被隐藏了,而第三个元素没有被隐藏.

The problem is when a page does not contain "Ribbon.ListForm.Display.Manage.Workflows-Medium" (the 2nd element) but contains "Ribbon.ListForm.Display.Manage.CheckOut-Large" (the 3rd element), the script will stop at in the middle with error [object is null or undefined]. Hence, 1st element is hided but 3rd element is not.

请问如何修改我的脚本?谢谢.

Could you please advice how to amend my script? Thank you.

推荐答案

因为 getElementById()返回null.

element是对 Element 对象的引用;如果为null,则为null一个元素 指定的ID不在文档中.

element is a reference to an Element object, or null if an element with the specified ID is not in the document.

您可以只检查真实值,而不必使用typeof测试

You can just check for the truthy value instead of use the typeof test

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

演示:小提琴

这篇关于如何处理getElementById返回Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆