javascript - 如何修复未捕获的类型错误 : Cannot read property 'href' of null

标签 javascript html

<分区>

当我调用 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)}

最佳答案

使用 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>

关于javascript - 如何修复未捕获的类型错误 : Cannot read property 'href' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704738/

相关文章:

javascript - EmberJS 中的隐藏/显示部分

javascript - 为什么我在使用 Vide 时收到 jQuery 错误 "url.indexOf is not a function"?

jquery - 如何更改已经在客户端的网页的字体?

javascript - 在图像上的一行上方制作文本

javascript - anchor 链接的平滑滚动不起作用

html - Div 作为广播 HTML5 CSS Bootstrap 3

javascript - 使用 Javascript 不会在 View 中调用 Controller 操作

javascript - ngResource 使用 $delete 从查询对象中删除记录

javascript - 为什么这个递归 javascript 函数不返回正确的值

html - 如何为标题单元格html设置默认宽度