本文介绍了跨浏览器,javascript getAttribute()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 试图确定一个体面的,跨浏览器的方法来获取javascript属性?假设javascript库使用(jQuery / Mootools / etc。)不是一个选项。trying to determine a decent, cross browser method for obtaining attributes with javascript? assume javascript library use (jQuery/Mootools/etc.) is not an option.我尝试了以下内容,但我经常得到属性是否为null IE尝试使用else方法时出现对象错误。任何人都可以提供帮助吗?I've tried the following, but I frequently get "attributes" is null or not an object error when IE tries to use the "else" method. Can anyone assist?<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,在每个浏览器中,我如何getAttr(ele,'href )? (假设选择ele节点不是问题)using the above html, in each browser, how do I getAttr(ele, 'href')? (assume selecting the ele node isn't an issue)推荐答案关于你的问题的更新,你可以试试这个。With regard to your question's update, you could try this.它可能有点过分,但如果 getAttribute()并且点表示法不返回结果,则遍历属性对象以尝试查找匹配。It may be overkill, but if getAttribute() and the dot notation don't return a result, it iterates through the attributes object to try to find a match. 示例: 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)It's up to you to do some cross-browser testing, though. :o)使用 ele.attributes ,你需要按索引访问它们,如:Using ele.attributes, you need to access them by index, as in:ele.attributes[0].nodeName; // "id" (for example)ele.attributes[0].nodeValue; // "my_id" (for example)尝试传递属性属性名称似乎返回 typeof object 的值,所以你的 else 代码正在运行,即使 ele.attributes [attr] 没有为您提供所需的值。Trying to pass attributes an attribute name appears to return a value whose typeof is object, so your else code is running even though ele.attributes[attr] doesn't give you the value you want. 这篇关于跨浏览器,javascript getAttribute()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 06-26 14:08