在JavaScript中检查节点值是否存在

3
我正在从已加载的AJAX页面中获取href值:每次加载AJAX页面时,它都会从新加载的页面中获取该值。
我使用以下代码来获取正确的href值: firstURL = l[0].childNodes[0].attributes[0].nodeValue; 然而,在最后一页上,此节点不存在(因为我们在最后一页),并返回:
Uncaught TypeError: Cannot read property 'attributes' of undefined trans.js:393
(anonymous function) trans.js:393
j jquery.min.js:2
k.fireWith jquery.min.js:2
x jquery.min.js:4
(anonymous function)

如果子节点 l[0].childNodes[0].attributes[0].nodeValue 存在,有没有一种方法可以将此变量赋值?


var firstURL = l[0].childNodes[0] ? l[0].childNodes[0].attributes[0].nodeValue : null; - adeneo
实际上,使用jQuery解决这个问题会更容易,因为jQuery可以处理空的匹配集合,从而覆盖了没有任何匹配结构可以进一步下降的情况。 - Thomas Urban
4个回答

2
您可以在尝试访问子节点之前先检查是否存在子节点:
var firstURL = '';

if(l[0].childNodes.length > 0){ // only if there's more than 1 child node
    firstURL = l[0].childNodes[0].attributes[0].nodeValue;
}

注意事项:

  • childNodes 包含文本节点,因此您可能更喜欢 children,它仅包含元素而不包含文本节点。如果将来在目标之前添加任何文本,则会获取文本节点。
  • 您可能更喜欢使用 getAttribute('href') 而不是获取存在的第一个属性。

要使用 .getAttribute(),只需像这样替换 .attributes[0]

firstURL = l[0].childNodes[0].getAttribute('href');

如果您将来给元素添加新属性,使用此方法会更加健壮。而依赖于它永远是第一个可能会引起问题。

另外请注意,如果您使用getAttribute(),则不需要访问nodeValue,因为getAttribute()直接返回实际的属性值。


谢谢!您能详细说明我如何在这种情况下使用getAttribute('href')吗? - user1469270
使用 firstURL = l[0].childNodes[0].getAttribute('href'); - Thomas Urban
@tmyie已添加到答案中 :) - MrCode

1

在解引用之前,您应该检查l[0].childNodes[0]是否存在。

if(l[0].childNodes[0]) {
    firstURL = l[0].childNodes[0].attributes[0].nodeValue;
} else {
    firstURL = <default value>;
}

或者作为三元运算符:

firstURL = (l[0].childNodes[0]) ? l[0].childNodes[0].attributes[0].nodeValue : <default value>;

0
if(!!l[0].childNodes[0]) {
    firstURL = l[0].childNodes[0].attributes[0].nodeValue;
}

1
请详细说明您的答案。 - Zane

0
使用jQuery(如问题中标记的那样),这可能变得非常容易:
var href = $('a.yourlink').attr('href');

由于$('a.yourlink')没有匹配到任何DOM元素,所以在最后一页上可能为空。但它不会抛出任何JS异常。因此,为了在最后一页上具有一些默认值,您可以将该代码段扩展如下:

var href = $('a.yourlink').attr('href') || 'my-default-url.html';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接