Javascript中 a.href 和 a.getAttribute('href') 结果不完全一致

今天无意中发现这个么问题,页面上对所有A标签的href属性为空的自动添加一个链接地址,结果发现if判断条件始终都没生效,莫名其妙。

原来Javascript中 a.href 和 a.getAttribute(‘href’) 结果在某些情况下是不完全一致的,以前从来都没注意过这个问题。

下面举个栗子:

<a href="">测试1</a>
<a href="#">测试2</a>
<a href="javascript:void(0)">测试3</a>
<script type="text/javascript">
var a = document.getElementsByTagName("a");
var it, href, href2;
for (var i=0; i<a.length; i++) {
    it = a.item(i);
    href = it.href;
    href2 = it.getAttribute('href');
    if (it.href == '' || it.href == '#') console.log('it.href: ', it.innerHTML);
    if (it.getAttribute('href') == '' || it.getAttribute('href') == '#') console.log('it.getAttribute("href"): ', it.innerHTML);
    console.log('['+ href +"]		"+ (href == href2 ? '==' : '!=') +"		["+ href2 +']');+']');
}
</script>

看看“测试一”和“测试二”,你可能以为 a.href 会输出 空字符串 和 # 号,但实际上他输出的是当前页面地址+# ,以前一直都没注意这么个问题。

// 对于 "测试一""测试二" 这个判断是不会生效的
if (it.href == '' || it.href == '#') console.log('it.href: ', it.innerHTML);

应该使用 getAttribute 方法来获取属性值

// 这样才正确
if (it.getAttribute('href') == '' || it.getAttribute('href') == '#') console.log('it.getAttribute("href"): ', it.innerHTML);

对比结果

Javascript中 a.href 和 a.getAttribute('href') 结果不完全一致

另外测试了下 form 表单的 action 属性也是一样的

原文地址:https://www.cnblogs.com/zhouzme/p/5758403.html