我应该使用哪个方法(.attr() vs .prop())的性能和使用

Which method should i use out of this(.attr() vs .prop()) for performance and usage?

本文关键字:prop 性能 vs attr 方法 我应该      更新时间:2023-09-26
$(selector).click(function(){
//instead of:
this.getAttribute('style');
//do i use:
$(this).prop('style');
//or:
$(this).attr('style');})

我已经解决了这个问题,并把我的解决方案放在"小提琴"下面。请检查一下……查看此页面:http://jsfiddle.net/maniator/JpUF2/

$.attr() vs $.prop()

这里有一个明确的答案解释简短

我在网上找不到任何完整的列表。每个给出列表的人都只是复制了jQuery 1.6博客文章中给出的部分列表。关于第三点,Starx在他的评论中回答了这个问题。http://timmywillison.com/通过一个体面的讨论进行了更详细的讨论。MDN和W3C规范还提到,可以像设置属性一样设置属性的各种接口(https://developer.mozilla.org/en/DOM/element),尽管MDN实际上并没有列出哪些是属性。MDN确实提到,使用属性接口作为setter比使用getAttribute:

更脆弱。

"虽然这些接口通常由大多数HTML和XML元素共享,但在DOM HTML规范中列出了针对特定对象的更专门的接口。但是请注意,这些HTML接口"仅适用于[HTML 4.01]和[XHTML 1.0]文档,不能保证与任何未来版本的XHTML一起工作"。HTML 5草案确实声明了它的目标是向后兼容这些HTML接口,但是说"一些以前被弃用的、不支持的、很少使用的或者被认为是不必要的特性已经被删除了。"可以通过完全使用DOM XML属性方法(如getAttribute())来避免潜在的冲突。"

然而,现在似乎可以安全地假设,在Firefox和Chrome中呈现的任何HTML5 doctype页面都已经处于"不推荐,不支持"等接口已经被删除的环境中。

因此,我已经测试了每个属性,以及jQuery博客中提到的非属性属性,针对每个HTML元素类型,使用布尔值、字符串和int值。

使用1.7.2和1.8pre,无论你调用。prop()还是attr(), jQuery都会在内部使用。prop:

async, autofocus, autoplay, checked, controls, defer, disabled, hidden, loop,
multiple, open, readonly, required, scoped, selected

对于HTML元素(这里不考虑window, document等),jQuery不会设置以下任何属性,除非你使用。attr():

accept-charset, accesskey, bgcolor, buffered, codebase, contextmenu, datetime,
default, dirname, dropzone, form, http-equiv, icon, ismap, itemprop, kind, 
language, list, location, manifest, nodeName, nodeType, novalidate, pubdate, 
radiogroup, seamless, selectedIndex, sizes, srclang, style, tagName

最后,jQuery将使用.prop()或.attr()设置以下属性列表。在上面的第一个列表中,jQuery总是使用.prop(),无论您使用的是.attr()还是.prop()。对于这个列表中的属性,jQuery使用您使用的任何属性。如果使用.prop(), jQuery使用.prop(),反之亦然。无论哪种情况,结果都是一样的。因此,忽略任何潜在的语义考虑,仅考虑prop()比。attr()快2.5倍,jQuery 1.6.1博客文章建议使用。attr(),但可以使用。prop(),性能显著提高:

accept, action, align, alt, autocomplete, border, challenge, charset, cite, 
class, code, color, cols, colspan, contenteditable, coords, data, defaultValue, 
dir, draggable, enctype, for, headers, height, hidden, high, href, hreflang, 
id, keytype, label, lang, low, max, maxlength, media, method, min, name, 
optimum, pattern, ping, placeholder, poster, preload, readonly, rel, required, 
reversed, rows, rowspan, sandbox, scope, shape, size, span, spellcheck, src, 
srcdoc, start, step, summary, tabindex, target, title, type, usemap, value, 
width, wrap

更多关于这个答案的信息请看点击这里

希望对您有所帮助....

$.prop() =>可以用来获取像tagName这样的DOM元素的属性,但是

$.attr() =>用于获取DOM元素的属性,如style。

有区别…

如果是你的HTML:

<div id='id' style="color: red;background: orange;">test</div>

和你的Javascript:

$("#id").click(function() {
    var getAtt = this.getAttribute('style');
    var thisProp = $(this).prop('style');
    var thisAttr = $(this).attr('style');
});

的区别

变量getAtt的值为color: red;background: orange;

thisProp的值是一个样式声明对象CSSStyleDeclaration

thisAttr的值为color: red;background: orange;


希望对你有所帮助