2015-03-25 74 views
0

在我们的Web应用程序中有许多页面。其中一些包含元素“Ribbon.ListForm.Display.Manage.Workflows-Medium”,而一些页面则不包含。如何处理getElementById返回空

我想用同样的脚本来检查对所有页面。该脚本将隐藏“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介质”(第2元素),但包含“Ribbon.ListForm.Display.Manage.CheckOut,大“(第三个元素),脚本将停在中间,出错[object is null or undefined]。因此,第一个元素是隐藏的,但第三个元素不是。

请您指点如何修改我的脚本?谢谢。

回答

2

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

元件是一个Element对象的引用或null如果具有指定ID的元素 不是在文档中。

你可以只检查了truthy值,而不是使用typeof测试

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

演示:Fiddle

1

您可以检查这样的空元素:

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

由于该问题使用jQuery进行标记:

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

首先,它会选择你感兴趣的元素;那么它会隐藏那些匹配基于值的简单过滤器。

+0

我不知道为什么,但上面的选择器似乎无法正常工作。 – Mark 2015-04-01 03:32:59

+0

@Mark更新了我的答案来解决这个问题,谢谢! – 2015-04-01 06:38:10

1

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

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。