.prop() vs .attr()
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>
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:
prop()
rather than attr()
. prop()
does what attr()
used to do. Replacing calls to attr()
with prop()
in your code will generally work. checked
property is a Boolean, the style
property is an object with individual properties for each style, the size
property is a number. 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). 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.
checked
attribute 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):
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | HTMLAnchorElement | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | 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 is not just an accessor for data-xyz
attributes [it does both more and less than that]; unless you actually need its features, I'd use the attr
function to interact with data-xyz
attribute.)
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
was meant to de-conflate them. Briefly in v1.6.0 jQuery went too far in that regard, but functionality was quickly added back to attr
to handle the common situations where people use attr
when technically they should use prop
.
This change has been a long time coming for jQuery. For years, they've been content with a function named attr()
that mostly retrieved DOM properties, not the result you'd expect from the name. The segregation of attr()
and prop()
should help alleviate some of the confusion between HTML attributes and DOM properties. $.fn.prop()
grabs the specified DOM property, while $.fn.attr()
grabs the specified HTML attribute.
To fully understand how they work, here's an extended explanation on the difference between HTML attributes and DOM properties.:
HTML Attributes
Syntax:
<body onload="foo()">
Purpose: Allows markup to have data associated with it for events, rendering, and other purposes.
Visualization: The class attribute is shown here on the body. It's accessible through the following code:
var attr;
attr = document.body.getAttribute("class");
//IE 8 Quirks and below
attr = document.body.getAttribute("className");
Attributes are returned in string form and can be inconsistent from browser to browser. However, they can be vital in some situations. As exemplified above, IE 8 Quirks Mode (and below) expects the name of a DOM property in get/set/removeAttribute instead of the attribute name. This is one of many reasons why it's important to know the difference.
DOM Properties
Syntax:
document.body.onload = foo;
Purpose: Gives access to properties that belong to element nodes. These properties are similar to attributes, but are only accessible through JavaScript. This is an important difference that helps clarify the role of DOM properties. Please note that attributes are completely different from properties , as this event handler assignment is useless and won't receive the event (body doesn't have an onload event, only an onload attribute).
Visualization:
Here, you'll notice a list of properties under the "DOM" tab in Firebug. These are DOM properties. You'll immediately notice quite a few of them, as you'll have used them before without knowing it. Their values are what you'll be receiving through JavaScript.
Documentation
Example
HTML: <textarea id="test" value="foo"></textarea>
JavaScript: alert($('#test').attr('value'));
In earlier versions of jQuery, this returns an empty string. In 1.6, it returns the proper value, foo
.
Without having glanced at the new code for either function, I can say with confidence that the confusion has more to do with the difference between HTML attributes and DOM properties, than with the code itself. Hopefully, this cleared some things up for you.
-Matt
链接地址: http://www.djcxy.com/p/718.html上一篇: 检查对象是否是数组?
下一篇: .prop()vs .attr()