zoukankan      html  css  js  c++  java
  • 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 属性也是一样的

  • 相关阅读:
    【DOS命令】type
    【shell】$符号操作
    【C++百科】STL(Standard Template Library) 标准模板库简介
    【配置与安装】SSH 密钥类型的的选择(RSA, DSA or Other)
    【百科通识】CPU x86/x86-64/x64/i386
    【配置与安装】SSH远程开发
    【百科通识】.bat文件
    【vi】模式切换
    【vim】撤销与回退
    【C++】智能指针
  • 原文地址:https://www.cnblogs.com/zhouzme/p/5758403.html
Copyright © 2011-2022 走看看