gpt4 book ai didi

javascript - 检查节点值是否存在于 JavaScript 中

转载 作者:行者123 更新时间:2023-11-29 10:43:58 26 4
gpt4 key购买 nike

我从加载的 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 = '';

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 直接返回()

关于javascript - 检查节点值是否存在于 JavaScript 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23154764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com