找到你要的答案

Q:.prop() vs .attr()

Q:attr()。prop() VS。

So jQuery 1.6 has the new function prop().

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

or in this case do they do the same thing?

And if I do have to switch to using prop(), all the old attr() calls will break if i switch to 1.6?

UPDATE

selector = '#id'

$(selector).click(function() {
    //instead of:
    var getAtt = this.getAttribute('style');
    //do i use:
    var thisProp = $(this).prop('style');
    //or:
    var thisAttr = $(this).attr('style');

    console.log(getAtt, thisProp, thisAttr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id='id' style="color: red;background: orange;">test</div>

(see also this fiddle: http://jsfiddle.net/maniator/JpUF2/)

The console logs the getAttribute as a string, and the attr as a string, but the prop as a CSSStyleDeclaration, Why? And how does that affect my coding in the future?

所以jQuery 1.6的新功能prop()。

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

或者在这种情况下,他们做同样的事情?

如果我有使用prop(),所有旧的attr()电话将我切换到1.6突破?

更新

selector = '#id'

$(selector).click(function() {
    //instead of:
    var getAtt = this.getAttribute('style');
    //do i use:
    var thisProp = $(this).prop('style');
    //or:
    var thisAttr = $(this).attr('style');

    console.log(getAtt, thisProp, thisAttr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id='id' style="color: red;background: orange;">test</div>

(参见此琴:http://jsfiddle.net/maniator/jpuf2/)

控制台日志中为一个字符串,并视为一个字符串,但作为一个cssstyledeclaration,为什么?这对我未来的编码有什么影响?

answer1: 回答1:

Update 1 November 2012

My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team reverted attr() to something close to (but not exactly the same as) its old behaviour for Boolean attributes. John Resig also blogged about it. I can see the difficulty they were in but still disagree with the recommendation to prefer attr().

Original answer

If you've only ever used jQuery and not the DOM directly, this could be a confusing change, although it is definitely an improvement conceptually. Not so good for the bazillions of sites using jQuery that will break as a result of this change though.

I'll summarize the main issues:

  • You usually want prop() rather than attr().
  • In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work.
  • Properties are generally simpler to deal with than attributes. An attribute value may only be a string whereas a property can be of any type. For example, the checked property is a Boolean, the style property is an object with individual properties for each style, the size property is a number.
  • Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as value and checked: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the defaultValue / defaultChecked property).
  • This change removes some of the layer of magic jQuery stuck in front of attributes and properties, meaning jQuery developers will have to learn a bit about the difference between properties and attributes. This is a good thing.

If you're a jQuery developer and are confused by this whole business about properties and attributes, you need to take a step back and learn a little about it, since jQuery is no longer trying so hard to shield you from this stuff. For the authoritative but somewhat dry word on the subject, there's the specs: DOM4, HTML DOM, DOM Level 2, DOM Level 3. Mozilla's DOM documentation is valid for most modern browsers and is easier to read than the specs, so you may find their DOM reference helpful. There's a section on element properties.

As an example of how properties are simpler to deal with than attributes, consider a checkbox that is initially checked. Here are two possible pieces of valid HTML to do this:

<input id="cb" type="checkbox" checked>
<input id="cb" type="checkbox" checked="checked">

So, how do you find out if the checkbox is checked with jQuery? Look on Stack Overflow and you'll commonly find the following suggestions:

  • if ( $("#cb").attr("checked") === true ) {...}
  • if ( $("#cb").attr("checked") == "checked" ) {...}
  • if ( $("#cb").is(":checked") ) {...}

This is actually the simplest thing in the world to do with the checked Boolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:

if (document.getElementById("cb").checked) {...}

The property also makes checking or unchecking the checkbox trivial:

document.getElementById("cb").checked = false

In jQuery 1.6, this unambiguously becomes

$("#cb").prop("checked", false)

The idea of using the checked attribute for scripting a checkbox is unhelpful and unnecessary. The property is what you need.

  • It's not obvious what the correct way to check or uncheck the checkbox is using the checked attribute
  • The attribute value reflects the default rather than the current visible state (except in some older versions of IE, thus making things still harder). The attribute tells you nothing about the whether the checkbox on the page is checked. See http://jsfiddle.net/VktA6/49/.

更新1十一月2012

我最初的回答具体适用于jQuery 1.6。我的建议是相同的但是jQuery 1.6.1改变的事物略:在破网站预测桩的脸,jQuery团队恢复attr()接近(但不完全相同)的布尔属性的旧行为。John Resig也在博客上写它。我能看到的困难他们还是不同意推荐喜欢attr()。

原来答案

如果你只使用jQuery DOM和不直接,这可能是一个混乱的变化,虽然它确实是一个改善的概念。不太适合使用jQuery将作为这种变化的结果,虽然网站的bazillions。

我将总结主要问题:

  • You usually want prop() rather than attr().
  • In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work.
  • Properties are generally simpler to deal with than attributes. An attribute value may only be a string whereas a property can be of any type. For example, the checked property is a Boolean, the style property is an object with individual properties for each style, the size property is a number.
  • Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as value and checked: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the defaultValue / defaultChecked property).
  • This change removes some of the layer of magic jQuery stuck in front of attributes and properties, meaning jQuery developers will have to learn a bit about the difference between properties and attributes. This is a good thing.

如果你是一个jQuery开发的整个业务特性和属性的混乱,你需要退后一步,学习一点关于它,因为jQuery是不再努力去保护你的东西。对于权威但主题有些干的话,还有规格:dom4,HTML DOM,DOM 2级,3级DOM。Mozilla的DOM文档的有效期是大多数现代浏览器,比天赋更容易阅读,所以你可能会发现他们的DOM参考帮助。元素属性有一节。

作为一个例子是如何性质的处理比属性简单,考虑一个复选框,初步检查。这里有两个可能有效的HTML做这件:

<input id="cb" type="checkbox" checked>
<input id="cb" type="checkbox" checked="checked">

那么,你如何找出如果复选框被选中与jQuery?看看堆栈溢出,你通常会发现以下建议:

  • if ( $("#cb").attr("checked") === true ) {...}
  • if ( $("#cb").attr("checked") == "checked" ) {...}
  • if ( $("#cb").is(":checked") ) {...}

这实际上是在世界上做的查布尔属性最简单的事,它一直存在,在每一个主要的脚本的浏览器完美工作自1995:

如果(文件。getElementById(“CB”)。检查){…}

这也使选中或取消选中复选框琐碎:

文件。getElementById(“CB”)。检查= false

在jQuery 1.6,这无疑成为

$(“# CB”)。道具(“检查”,假)

使用脚本检查属性复选框是无用的和不必要的想法。财产是你所需要的。

  • It's not obvious what the correct way to check or uncheck the checkbox is using the checked attribute
  • The attribute value reflects the default rather than the current visible state (except in some older versions of IE, thus making things still harder). The attribute tells you nothing about the whether the checkbox on the page is checked. See http://jsfiddle.net/VktA6/49/.
answer2: 回答2:

I think Tim said it quite well, but let's step back:

A DOM element is an object, a thing in memory. Like most objects in OOP, it has properties. It also, separately, has a map of the attributes defined on the element (usually coming from the markup that the browser read to create the element). Some of the element's properties get their initial values from attributes with the same or similar names (value gets its initial value from the "value" attribute; href gets its initial value from the "href" attribute, but it's not exactly the same value; className from the "class" attribute). Other properties get their initial values in other ways: For instance, the parentNode property gets its value based on what its parent element is; an element always has a style property, whether it has a "style" attribute or not.

Let's consider this anchor in a page at http://example.com/testing.html:

<a href='foo.html' class='test one' name='fooAnchor' id='fooAnchor'>Hi</a>

Some gratuitous ASCII art (and leaving out a lot of stuff):

+-------------------------------------------+
| a                                         |
+-------------------------------------------+
| href:       "http://example.com/foo.html" |
| name:       "fooAnchor"                   |
| id:         "fooAnchor"                   |
| className:  "test one"                    |
| attributes:                               |
|    href:  "foo.html"                      |
|    name:  "fooAnchor"                     |
|    id:    "fooAnchor"                     |
|    class: "test one"                      |
+-------------------------------------------+

Note that the properties and attributes are distinct.

Now, although they are distinct, because all of this evolved rather than being designed from the ground up, a number of properties write back to the attribute they derived from if you set them. But not all do, and as you can see from href above, the mapping is not always a straight "pass the value on", sometimes there's interpretation involved.

When I talk about properties being properties of an object, I'm not speaking in the abstract. Here's some non-jQuery code:

var link = document.getElementById('fooAnchor');
alert(link.href);                 // alerts "http://example.com/foo.html"
alert(link.getAttribute("href")); // alerts "foo.html"

(Those values are as per most browsers; there's some variation.)

The link object is a real thing, and you can see there's a real distinction between accessing a property on it, and accessing an attribute.

As Tim said, the vast majority of the time, we want to be working with properties. Partially that's because their values (even their names) tend to be more consistent across browsers. We mostly only want to work with attributes when there is no property related to it (custom attributes), or when we know that for that particular attribute, the attribute and the property are not 1:1 (as with href and "href" above).

The standard properties are laid out in the various DOM specs:

These specs have excellent indexes and I recommend keeping links to them handy; I use them all the time.

Custom attributes would include, for instance, any data-xyz attributes you might put on elements to provide meta-data to your code (now that that's valid as of HTML5, as long as you stick to the data- prefix). (Recent versions of jQuery give you access to data-xyz elements via the data function, but that function does more than that and if you're just dealing with a data-xyz attribute, I'd actually use the attr function to interact with it.)

The attr function used to have some convoluted logic around getting what they thought you wanted, rather than literally getting the attribute. It conflated the concepts. Moving to prop and attr is meant to de-conflate them. There will be some brief confusion, but hopefully a better understanding of what's really going on going forward.

Some time kicking around the specs above, and experimenting, should help clear some of this up.

Update: jQuery 1.6.1 changes the attr function again, in ways that the jQuery team say mean most code that currently uses attr will continue to work, even if prop would technically be preferred. Details in the jQuery 1.6.1 blog post.

我想提姆说得很好,但是我们退后一步:

一个DOM元素是一个对象,在记忆的事。像面向对象中的大多数对象,它的特性。此外,它还具有定义在元素上的属性的映射(通常来自浏览器读取创建元素的标记)。一些元素的性质,得到其初始值具有相同或类似名称的属性(价值获取初始值从“值”属性;链接从“href”属性,获取其初始值,但不完全相同的价值;从“类”的属性类名)。其他性能在其他途径获得的初始值:例如,其父节点属性获取其价值基于它的父元素是什么;一个元素总是一个样式属性,是否有一个“风格”属性或不。

让我们把这一页http://example.com/testing.html锚:

<a href='foo.html' class='test one' name='fooAnchor' id='fooAnchor'>Hi</a>

一些无端的ASCII艺术(留下了很多东西):

+-------------------------------------------+
| a                                         |
+-------------------------------------------+
| href:       "http://example.com/foo.html" |
| name:       "fooAnchor"                   |
| id:         "fooAnchor"                   |
| className:  "test one"                    |
| attributes:                               |
|    href:  "foo.html"                      |
|    name:  "fooAnchor"                     |
|    id:    "fooAnchor"                     |
|    class: "test one"                      |
+-------------------------------------------+

注意属性和属性是不同的。

现在,虽然它们是不同的,因为所有这一切的演变,而不是从地面设计,一些属性写回属性,他们来自于如果你设置它们。但并不是所有的做,正如你可以看到从上面的链接,映射不一定是直线”“传递价值,有时有解释涉及。

当我谈论属性是一个对象的属性时,我不是在抽象。这里的一些非jQuery代码:

var link = document.getElementById('fooAnchor');
alert(link.href);                 // alerts "http://example.com/foo.html"
alert(link.getAttribute("href")); // alerts "foo.html"

(这些值与大多数浏览器一样;有些变化。)

链接对象是一个真实的东西,你可以看到访问它的属性和访问属性之间有真正的区别。

正如提姆所说,绝大多数的时候,我们希望能与物业合作。部分是因为他们的价值观(甚至他们的名字)往往更一致的浏览器。我们大多只想工作的时候没有财产属性与它(自定义属性),或当我们知道特定的属性,属性和属性不是1:1(如href和“href”以上)。

标准属性放在不同的DOM规范:

这些规格有优秀的索引,我建议保持链接到他们方便,我一直使用它们。

自定义属性可以包括,例如,任何数据XYZ属性你可能把你的代码元素提供元数据(现在的有效作为HTML5的,只要你坚持数据的前缀)。(jQuery的最新版本给你访问数据XYZ元素通过数据功能,但功能不多,如果你只处理一个数据XYZ属性,我会使用attr函数与它进行交互。)

attr函数用于一些复杂的逻辑在得到他们想要的,而不是从字面上得到的属性。它糅合了概念。移动到道具和属性是为了去将他们。会有一些短暂的混乱,但希望更好地了解什么是真正的前进。

一些时间踢上面的规格,和实验,应该有助于清除一些这。

更新:jQuery 1.6.1 attr函数变化的方式,再次,jQuery团队说的大多数代码,目前使用的属性将继续工作,即使支撑会技术优先。在jQuery 1.6.1博客细节。

javascript  jquery  dom  attr  prop