如何修复未捕获的TypeError:无法读取null的属性'href'[重复]

问题描述 投票:1回答:2

看来,当我调用if(test.href!=“https://www.test.com”)时,它给了我一个空值,但我不确定为什么,因为我期望它返回URL

HTML

<p><a id="damn" href="https://www.test.com" target="_self">PC Install</a></p>

JS脚本:

var test= document.getElementById("damn");
if (test.href != "https://www.test.com") {console.log(test)}
javascript html html5 webpage
2个回答
1
投票

使用getAttribute,它的工作原理。

var test = document.getElementById("damn");
if (test.getAttribute("href") != "https://www.test.com") {
  console.log(test)
}
<p><a id="damn" href="https://www.test.com" target="_self">PC Install</a></p>

0
投票

尝试重新排序代码,并将脚本放在'a'标记之后。

© www.soinside.com 2019 - 2024. All rights reserved.