我有根“客户端”的xml数据,它可以包含多个“客户端”元素。有时在XML文件中没有返回客户端元素(这没关系)。我需要确定是否有任何客户端元素返回,所以我尝试使用:
if(typeof myfile.getElementsByTagName("client")){
alert("no clients");
}
这可以完成预期的工作,但只要没有“客户端”元素,我就会收到一个firebug错误。
答案 0 :(得分:10)
为什么不检查NodeList的长度?
if( myfile.getElementsByTagName("client").length == 0 )
{
alert("no clients");
}
添加此项以检查myfile是否已定义
if( typeof myfile == "undefined" || myfile.getElementsByTagName("client").length == 0 )
{
alert("no clients");
}
答案 1 :(得分:3)
尝试:
if (!myfile.getElementsByTagName("client").length) {}
// ^ falsy (0) if no elements
如果您不确定myfile
作为元素存在,则应首先检查:
if (typeof myfile !== 'undefined'
&& myfile.getElementsByTagName
&& myfile.getElementsByTagName("client").length) {}