跨浏览器的javascript getAttribute()方法?

15

尝试找到一种不依赖于JavaScript库(如jQuery/Mootools等)的跨浏览器获取属性的方法?

我已经尝试了以下方法,但当IE尝试使用"else"方法时,经常会出现"attributes"为null或不是对象错误。 有人能帮忙吗?

<script type="text/javascript">
//...
    getAttr: function(ele, attr) {
      if (typeof ele.attributes[attr] == 'undefined'){
        return ele.getAttribute(attr);
      } else {
        return ele.attributes[attr].nodeValue;
      }
    },
//...
</script>


<div>
 <a href="http://www.yo.com#foo">Link</a>
</div>

使用上述HTML,在每个浏览器中,如何获取Attr(ele, 'href')?(假设选择ele节点不是问题)

3个回答

16
大多数情况下,您可以简单地使用内置的getAttribute函数。

例如:
ele.getAttribute(attr)

根据QuirksMode的说法,这应该在所有主流浏览器(包括IE >= 6)上都能正常工作,只有一个小例外:
在IE5-7中,访问style属性会得到一个对象,而访问onclick属性会得到一个将实际内容包装起来的匿名函数。

10

关于您问题的更新,您可以尝试以下方法。

可能有点过度解决,但如果getAttribute()和点符号运算不能返回结果,则通过迭代attributes对象来尝试查找匹配项。

示例:http://jsfiddle.net/4ZwNs/

var funcs = {
    getAttr: function(ele, attr) {
        var result = (ele.getAttribute && ele.getAttribute(attr)) || null;
        if( !result ) {
            var attrs = ele.attributes;
            var length = attrs.length;
            for(var i = 0; i < length; i++)
                if(attrs[i].nodeName === attr)
                    result = attrs[i].nodeValue;
        }
        return result;
    }
};

var result = funcs.getAttr(el, 'hash');

不过跨浏览器测试是由你自己来完成的。:o)


使用ele.attributes,你需要通过索引访问它们,如:

ele.attributes[0].nodeName;   // "id" (for example)
ele.attributes[0].nodeValue;  // "my_id" (for example)

尝试传递attributes时,属性名称似乎返回一个typeofobject的值,因此即使ele.attributes[attr]没有提供您想要的值,您的else代码也会运行。


@tester - 在IE7和IE8中对我有效。也许尝试用(ele.getAttribute && ele.getAttribute(attr))替换ele.getAttribute(attr)。编辑:如果是选择器的问题,请告诉我。 - user113716
@tester - 已更新答案。请查看@Tim Down上面的评论。 - user113716
1
也许我来晚了,但我认为这里有一个错别字。我想你在循环中应该使用attrs[i].nodeNameattrs[i].nodeValue - Craig
测试 if( !result ) 是否意味着 false-y 结果(如空字符串)会导致循环运行?建议改用 if (result !== null)。 - enigment
1
@enigment 你是正确的,而且如果getAttribute方法存在但属性未设置,则无需循环。所以我会将if条件更改为(result!== null &&!ele.getAttribute) - gigaDIE
显示剩余10条评论

5

您试图在确定这些属性是否存在之前访问ele的属性。尝试使用此类证据链:

if (ele.attributes && ele.attributes[attr] && typeof ele.attributes[attr] == 'undefined')

etc.


我想这样做可以消除我的错误(谢谢),但是我该如何使用我的方法$.getAttr($anchor,'href');在IE6-8中,我如何从<a href="#">获取href? - tester
抱歉,我不确定你在问什么。 - Robusto
我更新了问题底部以明确我的目标(所选链接的href)。 - tester

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接