-1
$(selector).click(function(){
//instead of:
this.getAttribute('style');
//do i use:
$(this).prop('style');
//or:
$(this).attr('style');})

我已经解决了这个问题,并将我的解决方案放在“小提琴”下面。请检查它...看到这个小提琴:http: //jsfiddle.net/maniator/JpUF2/

希望这会有所帮助...

4

3 回答 3

2

$.attr() 与 $.prop()

这里有一个明确的答案解释了breif

我在网上找不到任何完整的清单。每个给出任何类型列表的人都只是复制 jQuery 1.6 博客文章中给出的部分列表。关于#3,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 文档类型页面已经处于“已弃用、支持不佳”等接口已被删除的环境中。

因此,我使用 boolean、string 和 int 值针对每种 HTML 元素类型测试了每个属性以及 jQuery 博客中提到的非属性属性。

使用 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 元素(此处不考虑窗口、文档等),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

更清楚这个答案看看点击这里

希望这可以帮助....

于 2014-07-11T10:25:07.467 回答
0

它们是有区别的...

如果这是您的 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;


希望它有所帮助:)

于 2014-07-11T10:25:06.520 回答
0

$.prop() => 可用于获取 DOM 元素的属性,如 tagName 但

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

于 2014-07-11T10:14:24.487 回答