检索HTML属性值“DOM 0路” [英] Retrieving HTML attribute values "the DOM 0 way"
问题描述
jQuery有一个 attr()
方法,用于检索给定HTML属性的值。例如:
jQuery has an attr()
method which retrieves the value of a given HTML attribute. For instance:
var foo = document.getElementById("foo");
$(foo).attr("id");
但是,性能方面这不是最优的,因为jQuery对象必须创建只是为了调用 attr()
方法。这表现更好: foo.id
。
But, performance-wise this is not optimal since an jQuery object has to be created just to call the attr()
method. This performs better: foo.id
.
因此,理想情况下,我们希望避免使用 attr()
。但是,我们可以这样做(对于任何属性)?我相信 foo.id
和 foo.value
是安全(跨浏览器),但我记得有问题与 foo.href
。
So, ideally we would want to avoid using attr()
. But, can we do that (for any attribute)? I believe foo.id
and foo.value
is "safe" (cross-browser), but I remember having issues with foo.href
.
这里是一个列表的各种属性,我想要能够检索直接:
Here is a list of various attributes that I would like to be able to retrieve "directly":
对于任何元素: foo.id
, foo.name
锚点: foo.href
, foo.target
,
foo.rel
对于图像,对象,iframes: foo.src
,
foo.width
, foo.height
对于表单元素: foo.checked
, foo.selected
, foo.disabled
, foo.readonly
, foo.type
, foo.value
, foo.action
For any element: foo.id
, foo.name
For anchors: foo.href
, foo.target
, foo.rel
For images, objects, iframes: foo.src
, foo.width
, foo.height
For form elements: foo.checked
, foo.selected
, foo.disabled
, foo.readonly
, foo.type
, foo.value
, foo.action
所以问题是:Are上面的表达式是跨浏览器?我可以安全地使用它们吗?
So the question is: Are the above expressions cross-browser? Can I use them safely?
检查此问题的文章的链接也很不错。
A link to an article which examines this issue would also be nice.
推荐答案
查看jQuery如何处理它:
Looking at how jQuery handles it:
- href,src和style属性需要特殊处理。
- Safari有一个错误访问select元素上的selected属性。如果访问selected属性,Safari需要特殊处理。
查看 jQuery源,并搜索此行以查看特殊处理的含义:
attr:function(elem,name,value,pass){
Check out the jQuery source, and search for this line to see what I mean by "special treatment":
attr: function( elem, name, value, pass ) {
总之:想要的大多数属性列出,除了上面显示的那些。
为了方便起见,您可以这样做:
In short: I think it safe to do what you want for most of the attributes listed, except for those shown above.
To keep things easy, you could do this:
$foo = $("#foo");
console.log( $foo.attr("id"), $foo.attr("style"), $foo.attr("href") );
只有1个jQuery对象被创建,你不必担心手动处理任何东西。
Only 1 jQuery object is made, and you don't have to worry about manually handling anything.
这篇关于检索HTML属性值“DOM 0路”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!