.prop() 与 .attr()
因此 jQuery 1.6 具有新功能 prop()
。
$(selector).click(function(){
//instead of:
this.getAttribute('style');
//do i use:
$(this).prop('style');
//or:
$(this).attr('style');
})
或者在这种情况下他们做同样的事情吗?
如果我确实必须切换到使用prop()
,那么如果我切换到1.6,所有旧的attr()
调用都会中断?
更新
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/)
控制台日志getAttribute
作为字符串,attr
作为字符串,但 prop
作为 CSSStyleDeclaration
,为什么?这对我将来的编码有何影响?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(18)
2012 年 11 月 1 日更新
我原来的答案特别适用于 jQuery 1.6。我的建议保持不变,但 jQuery 1.6.1 略有改变:面对预计的一堆损坏的网站,jQuery 团队 将
attr()
恢复为接近(但不完全相同)布尔属性的旧行为。 John Resig 也在博客上介绍了它。我可以看到他们面临的困难,但仍然不同意他更喜欢attr()
的建议。原始答案
如果您只使用过 jQuery 而不是直接使用 DOM,那么这可能是一个令人困惑的更改,尽管它在概念上绝对是一个改进。不过,对于大量使用 jQuery 的网站来说,情况不太好,这些网站将因这一更改而崩溃。
我将总结主要问题:
prop()
而不是attr()
。prop()
执行attr()
过去的操作。在代码中用prop()
替换对attr()
的调用通常会起作用。checked
属性是一个布尔值,style
属性是一个对象,每个样式都有单独的属性,size
属性是一个数字。value
和checked:对于这些属性,属性始终表示当前状态,而属性(旧版本的 IE 除外)对应于输入的默认值/检查性(反映在
defaultValue
/defaultChecked
属性)。如果您是一名 jQuery 开发人员,并且对属性和属性的整个业务感到困惑,那么您需要退后一步并了解一些知识,因为 jQuery 不再努力保护您免受这些东西的影响。对于该主题的权威但有些枯燥的词,有规范:DOM4,HTML DOM,DOM 级别 2、DOM 级别 3< /a>. Mozilla 的 DOM 文档适用于大多数现代浏览器,并且比规范更容易阅读,因此您可以找到他们的 DOM 参考 有帮助。有一个关于元素属性的部分。
作为属性比属性更容易处理的示例,请考虑最初选中的复选框。这里有两个可能的有效 HTML 片段来执行此操作:
那么,如何确定复选框是否已使用 jQuery 选中?查看 Stack Overflow,您通常会发现以下建议:
if ( $("#cb").attr("checked") === true ) {...}
if ( $("#cb").attr("checked") == "checked" ) {...}
if ( $("#cb").is(":checked" ) ) {...}
这实际上是使用
checked
布尔属性是世界上最简单的事情,自 1995 年以来,该属性一直在每个主要的可编写脚本的浏览器中存在并完美运行:if (document.getElementById("cb").checked) {...}
该属性还使得选中或取消选中复选框变得微不足道:
document.getElementById("cb").checked = false
在 jQuery 1.6 中,这明确地变为
$("#cb").prop("checked", false)
使用
checked
属性编写复选框脚本的想法是没有帮助且不必要的。该属性就是您所需要的。checked
属性来检查或取消选中复选框的正确方法并不明显该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 his recommendation to preferattr()
.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 thanattr()
.prop()
does whatattr()
used to do. Replacing calls toattr()
withprop()
in your code will generally work.checked
property is a Boolean, thestyle
property is an object with individual properties for each style, thesize
property is a number.value
andchecked
: 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 thedefaultValue
/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:
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我认为 Tim 说得很好,但让我们退一步:
DOM 元素是一个对象,记忆中的东西。与 OOP 中的大多数对象一样,它具有属性。它还单独具有元素上定义的属性的映射(通常来自浏览器读取以创建元素的标记)。元素的某些属性从具有相同或相似名称的属性获取其初始值(
值
获取其初始值来自“value”属性的值;href
从“href”属性获取其初始值,但它与来自“class”属性的className
值不完全相同) 。其他属性以其他方式获取其初始值:例如,parentNode 属性根据其父元素获取其值;元素始终具有style
属性,无论它是否具有“style”属性。让我们考虑一下
http://example.com/testing.html
页面中的这个锚点:一些无偿的 ASCII 艺术(并省略了很多内容):
请注意,属性和属性是不同的。
现在,尽管它们是不同的,但由于所有这些都是进化而来的而不是从头开始设计的,因此如果您设置它们,许多属性会写回它们派生的属性。但并非所有人都这样做,正如您从上面的
href
中看到的,映射并不总是直接“传递值”,有时还涉及解释。当我谈论属性是对象的属性时,我并不是在抽象地谈论。下面是一些非 jQuery 代码:
link
对象是真实存在的,您可以看到访问其上的属性 和访问 之间存在真正的区别属性。正如蒂姆所说,绝大多数时间,我们希望与房地产合作。部分原因是它们的值(甚至它们的名称)在不同浏览器中往往更加一致。我们大多只想在没有与属性相关的属性(自定义属性)时使用属性,或者当我们知道对于该特定属性,属性和属性不是 1:1(如
href 和上面的“href”)。
标准属性在各种 DOM 规范中列出:
这些规范有很好的索引,我建议保留它们的链接;我一直在使用它们。
例如,自定义属性将包括您可能放置在元素上的任何
data-xyz
属性,以便为您的代码提供元数据(现在这在 HTML5 中是有效的,只要您坚持 <代码>数据-前缀)。 (jQuery 的最新版本允许您通过data
函数访问data-xyz
元素,但该函数不只是的访问器>data-xyz
属性 [它的作用既多又少];除非您确实需要它的功能,否则我会使用attr
函数与data-xyz 交互 。)
属性 attr 函数过去有一些复杂的逻辑来获取他们认为你想要的东西,而不是字面上获取属性。它混淆了概念。转向
prop
和attr
的目的是为了消除它们的混淆。简而言之,在 v1.6.0 中,jQuery 在这方面走得太远了,但是功能 很快被添加回attr
中,以处理人们在技术上应该使用prop< 时却使用
attr
的常见情况/代码>。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, theparentNode
property gets its value based on what its parent element is; an element always has astyle
property, whether it has a "style" attribute or not.Let's consider this anchor in a page at
http://example.com/testing.html
:Some gratuitous ASCII art (and leaving out a lot of stuff):
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:
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 thedata-
prefix). (Recent versions of jQuery give you access todata-xyz
elements via thedata
function, but that function is not just an accessor fordata-xyz
attributes [it does both more and less than that]; unless you actually need its features, I'd use theattr
function to interact withdata-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 toprop
andattr
was meant to de-conflate them. Briefly in v1.6.0 jQuery went too far in that regard, but functionality was quickly added back toattr
to handle the common situations where people useattr
when technically they should useprop
.对于 jQuery 来说,这一变化已经等待很长时间了。多年来,他们一直满足于一个名为
attr()
的函数,该函数主要检索 DOM 属性,而不是您期望从名称中获得的结果。attr()
和prop()
应该有助于缓解 HTML 属性和 DOM 属性之间的一些混淆。$.fn.prop()
获取指定的 DOM 属性,而$.fn.attr()
获取指定的 HTML 属性。为了充分理解它们的工作原理,这里对 HTML 属性和 DOM 属性之间的区别进行了扩展解释。
: HTML 属性
语法:
用途:
允许标记具有与其关联的数据以用于事件、呈现和其他目的。
可视化:
类属性显示在正文上。可以通过以下代码访问它:
属性以字符串形式返回,并且在不同的浏览器中可能不一致。然而,它们在某些情况下可能至关重要。如上所示,IE 8 Quirks Mode(及以下版本)需要 get/set/removeAttribute 中的 DOM 属性名称,而不是属性名称。这是了解差异很重要的众多原因之一。
DOM 属性
语法:
document.body.onload = foo;
用途:
允许访问属于元素节点的属性。这些属性与属性类似,但只能通过 JavaScript 访问。这是一个重要的区别,有助于阐明 DOM 属性的作用。 请注意,属性与属性完全不同,因为此事件处理程序分配是无用的,不会接收事件(主体没有 onload 事件,只有 onload 属性)。
可视化:
在这里,您会注意到 Firebug 中“DOM”选项卡下的属性列表。这些是 DOM 属性。您会立即注意到其中的很多,因为您之前已经使用过它们而不自知。它们的值是您将通过 JavaScript 接收到的值。
文档
David Flanagan
Mozilla 开发中心
示例
HTML :
JavaScript:
alert($('#test').attr('value'));
在 jQuery 的早期版本中,这会返回一个空字符串。在 1.6 中,它返回正确的值
foo
。在没有浏览这两个函数的新代码的情况下,我可以自信地说,这种混乱更多地与 HTML 属性和 DOM 属性之间的差异有关,而不是与代码本身有关。希望这能为您清除一些事情。
-马特
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 ofattr()
andprop()
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:
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
David Flanagan
Mozilla Dev Center
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
属性位于 DOM 中;属性位于被解析到 DOM 中的 HTML 中。
更多详细信息
如果更改属性,更改将反映在 DOM 中(有时使用不同的名称)。
示例:更改标签的
class
属性将更改 DOM 中该标签的className
属性(这是因为class
是JavaScript 并且不能用于属性名称)。如果标签上没有属性,则相应的 DOM 属性仍然具有空值或默认值。
示例:虽然您的标记没有
class
属性,但 DOM 属性className
确实存在且具有空字符串值。编辑
如果您更改其中一个,另一个将由控制器更改,反之亦然。
该控制器不在 jQuery 中,而是在浏览器的本机代码中。
A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.
Further detail
If you change an attribute, the change will be reflected in the DOM (sometimes with a different name).
Example: Changing the
class
attribute of a tag will change theclassName
property of that tag in the DOM (That's becauseclass
is a reserved word in JavaScript and can't be used for a property name).If you have no attribute on a tag, you still have the corresponding DOM property with an empty or a default value.
Example: While your tag has no
class
attribute, the DOM propertyclassName
does exist with a empty string value.edit
If you change the one, the other will be changed by a controller, and vice versa.
This controller is not in jQuery, but in the browser's native code.
只是 HTML 属性和 DOM 对象之间的区别导致了混淆。对于那些熟悉 DOM 元素本机属性(例如
this.src
this.value
this.checked
等)的人来说,. prop
是对这个家庭的热烈欢迎。对于其他人来说,这只是增加了一层混乱。让我们澄清一下。查看
.attr
和.prop
之间差异的最简单方法是以下示例:$('input').attr('blah' )
:按预期返回'hello'
。这里没有什么惊喜。$('input').prop('blah')
:返回undefined
- 因为它正在尝试执行[HTMLInputElement] .blah
——该 DOM 对象上不存在这样的属性。它仅作为该元素的属性存在于范围内,即[HTMLInputElement].getAttribute('blah')
现在我们更改一些内容,如下所示:
$('input' ).attr('blah')
:返回'apple'
嗯?为什么不使用“pear”,因为这是在该元素上最后设置的。因为属性是在输入属性上更改的,而不是 DOM 输入元素本身 - 它们基本上几乎彼此独立工作。$('input').prop('blah')
: returns'pear'
你真正需要小心的是由于上述原因,请勿在整个应用程序中对同一属性混合使用这些属性。
查看演示差异的小提琴: http://jsfiddle.net/garreh/uLQXc/
.attr
vs.prop
:第 1 轮:样式
.attr('style')
-- 返回匹配的内联样式元素即"font:arial;"
.prop('style')
-- 返回样式声明对象,即CSSStyleDeclaration
第二轮:值
.attr('value')
-- 返回'hello'
*.prop('value')
-- 返回'我更改了值'
* 注意:jQuery 为此有一个
.val()
方法,其内部相当于.prop('value')
It's just the distinction between HTML attributes and DOM objects that causes a confusion. For those that are comfortable acting on the DOM elements native properties such a
this.src
this.value
this.checked
etc,.prop
is a very warm welcome to the family. For others, it's just an added layer of confusion. Let's clear that up.The easiest way to see the difference between
.attr
and.prop
is the following example:$('input').attr('blah')
: returns'hello'
as expected. No suprises here.$('input').prop('blah')
: returnsundefined
-- because it's trying to do[HTMLInputElement].blah
-- and no such property on that DOM object exists. It only exists in the scope as an attribute of that element i.e.[HTMLInputElement].getAttribute('blah')
Now we change a few things like so:
$('input').attr('blah')
: returns'apple'
eh? Why not "pear" as this was set last on that element. Because the property was changed on the input attribute, not the DOM input element itself -- they basically almost work independently of each other.$('input').prop('blah')
: returns'pear'
The thing you really need to be careful with is just do not mix the usage of these for the same property throughout your application for the above reason.
See a fiddle demonstrating the difference: http://jsfiddle.net/garreh/uLQXc/
.attr
vs.prop
:Round 1: style
.attr('style')
-- returns inline styles for the matched element i.e."font:arial;"
.prop('style')
-- returns an style declaration object i.e.CSSStyleDeclaration
Round 2: value
.attr('value')
-- returns'hello'
*.prop('value')
-- returns'i changed the value'
* Note: jQuery for this reason has a
.val()
method, which internally is equivalent to.prop('value')
TL;DR
在大多数情况下,使用
prop()
而不是attr()
。属性是输入元素的当前状态。 属性是默认值。
属性可以包含不同类型的事物。属性只能包含字符串
TL;DR
Use
prop()
overattr()
in the majority of cases.A property is the current state of the input element. An attribute is the default value.
A property can contain things of different types. An attribute can only contain strings
脏检查
这个概念提供了一个可以观察到差异的示例:http://www.w3.org/TR/html5/forms.html#concept-input-checked-dirty
尝试一下:
prop
复选框。砰!对于某些属性,例如
button
上的disabled
,添加或删除内容属性disabled="disabled"
始终会切换属性(在 HTML5 中称为 IDL 属性) )因为 http://www.w3.org/TR/html5 /forms.html#attr-fe-disabled 说:所以你可能会逃脱它,尽管它很丑陋,因为它不需要修改 HTML。
对于其他属性,例如
input type="checkbox"
上的checked="checked"
,事情会中断,因为一旦单击它,它就会变脏,然后添加或删除checked="checked"
内容属性不再切换选中状态。这就是为什么您应该主要使用
.prop
,因为它直接影响有效属性,而不是依赖于修改 HTML 的复杂副作用。Dirty checkedness
This concept provides an example where the difference is observable: http://www.w3.org/TR/html5/forms.html#concept-input-checked-dirty
Try it out:
prop
checkbox got checked. BANG!For some attributes like
disabled
onbutton
, adding or removing the content attributedisabled="disabled"
always toggles the property (called IDL attribute in HTML5) because http://www.w3.org/TR/html5/forms.html#attr-fe-disabled says:so you might get away with it, although it is ugly since it modifies HTML without need.
For other attributes like
checked="checked"
oninput type="checkbox"
, things break, because once you click on it, it becomes dirty, and then adding or removing thechecked="checked"
content attribute does not toggle checkedness anymore.This is why you should use mostly
.prop
, as it affects the effective property directly, instead of relying on complex side-effects of modifying the HTML.全部内容都在文档中:
所以使用道具!
All is in the doc:
So use prop!
属性位于您的 HTML 文本文档/文件中(==想象这是您的 html 标记解析的结果),而
属性位于 HTML DOM 树中(==基本上是 JS 意义上某个对象的实际属性)。
重要的是,其中许多都是同步的(如果更新
class
属性,html 中的class
属性也会更新;否则)。 但是某些属性可能会同步到意外的属性 - 例如,属性checked
对应于属性defaultChecked< /code>,这样
.prop('checked')
值,但不会更改.attr('checked')
和.prop('defaultChecked')
值$('#input').prop('defaultChecked', true)
也会更改.attr('checked')
,但这在一个元素。这是一个表格,显示了
.prop()
是首选(虽然.attr()
仍然可以使用)。为什么你有时想要使用 .prop() 而不是 .attr(),后者是官方建议的?
.prop()
可以返回任何类型 - 字符串、整数、布尔值;而.attr()
始终返回一个字符串。.prop()
比.attr()
快约 2.5 倍。attributes are in your HTML text document/file (== imagine this is the result of your html markup parsed), whereas
properties are in HTML DOM tree (== basically an actual property of some object in JS sense).
Importantly, many of them are synced (if you update
class
property,class
attribute in html will also be updated; and otherwise). But some attributes may be synced to unexpected properties - eg, attributechecked
corresponds to propertydefaultChecked
, so that.prop('checked')
value, but will not change.attr('checked')
and.prop('defaultChecked')
values$('#input').prop('defaultChecked', true)
will also change.attr('checked')
, but this will not be visible on an element.And here is a table that shows where
.prop()
is preferred (even though.attr()
can still be used).Why would you sometimes want to use .prop() instead of .attr() where latter is officially adviced?
.prop()
can return any type - string, integer, boolean; while.attr()
always returns a string..prop()
is said to be about 2.5 times faster than.attr()
..attr()
:.prop()
:.attr()
:.prop()
:通常您会想要使用属性。
仅将属性用于:
。
Usually you'll want to use properties.
Use attributes only for:
<input value="abc">.
属性
-> HTML属性
-> DOMattributes
-> HTMLproperties
-> DOM在 jQuery 1.6 之前,
attr()
方法有时在检索属性时会考虑属性值,这会导致行为相当不一致。prop()
方法的引入提供了一种显式检索属性值的方法,而.attr()
则检索属性。文档:
jQuery.attr()
获取匹配元素集中第一个元素的属性值。
jQuery.prop()
获取匹配元素集中第一个元素的属性值。
Before jQuery 1.6 , the
attr()
method sometimes took property values into account when retrieving attributes, this caused rather inconsistent behavior.The introduction of the
prop()
method provides a way to explicitly retrieve property values, while.attr()
retrieves attributes.The Docs:
jQuery.attr()
Get the value of an attribute for the first element in the set of matched elements.
jQuery.prop()
Get the value of a property for the first element in the set of matched elements.
.attr()
可以做.prop()
不能做的一件事:影响 CSS 选择器这是我在其他答案中没有看到的问题。
CSS 选择器
[name=value]
.attr('name', 'value')
.prop('name', ' value')
.prop()
仅影响少数属性选择器输入[名称]
(感谢@TimDown).attr()
影响所有属性选择器input[值]
输入[naame]
span[名称]
input[data-custom-attribute]
(也不会.data('custom-attribute ')
影响此选择器)One thing
.attr()
can do that.prop()
can't: affect CSS selectorsHere's an issue I didn't see in the other answers.
CSS selector
[name=value]
.attr('name', 'value')
.prop('name', 'value')
.prop()
affects only a few attribute-selectorsinput[name]
(thanks @TimDown).attr()
affects all attribute-selectorsinput[value]
input[naame]
span[name]
input[data-custom-attribute]
(neither will.data('custom-attribute')
affect this selector)温馨提示
prop()
的使用,例如:上面的函数用于检查checkbox1是否被选中,如果选中:return 1;如果不是:返回 0。这里使用 prop() 函数作为 GET 函数。
上面的函数用于设置 checkbox1 被选中并始终返回 1。现在函数 prop() 用作 SET 函数。
别搞砸了。
P/S:当我检查图像src属性时。如果src为空,则prop返回页面的当前URL(错误),attr返回空字符串(右)。
Gently reminder about using
prop()
, example:The function above is used to check if checkbox1 is checked or not, if checked: return 1; if not: return 0. Function prop() used here as a GET function.
The function above is used to set checkbox1 to be checked and ALWAYS return 1. Now function prop() used as a SET function.
Don't mess up.
P/S: When I'm checking Image src property. If the src is empty, prop return the current URL of the page (wrong), and attr return empty string (right).
prop() 与 attr() 之间还有一些注意事项:
selectedIndex、tagName、nodeName、nodeType、ownerDocument、defaultChecked 和 defaultSelected..etc 应使用 .prop() 方法检索和设置。这些没有相应的属性,只是属性。
对于输入类型复选框
prop 方法返回布尔值,表示选中、选定、禁用、
readOnly..etc 而 attr 返回定义的字符串。所以,你可以直接
在 if 条件中使用 .prop('checked')。
.attr() 在内部调用 .prop(),因此 .attr() 方法会略有不同
比直接通过 .prop() 访问它们要慢。
There are few more considerations in prop() vs attr():
selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected..etc should be retrieved and set with the .prop() method. These do not have corresponding attributes and are only properties.
For input type checkbox
prop method returns Boolean value for checked, selected, disabled,
readOnly..etc while attr returns defined string. So, you can directly
use .prop(‘checked’) in if condition.
.attr() calls .prop() internally so .attr() method will be slightly
slower than accessing them directly through .prop().
我们主要想用于 DOM 对象而不是自定义属性
例如
data-img, data-xyz
。访问
checkbox
值和href
时也存在一些差异随着 DOM 输出的变化,使用
attr()
和prop()
prop()
作为来自origin
的完整链接和复选框的Boolean
值(1.6 之前)
我们只能使用
prop
访问 DOM 元素,否则它会给出undefined
< /p>Mostly we want to use for DOM object rather then custom attribute
like
data-img, data-xyz
.Also some of difference when accessing
checkbox
value andhref
with
attr()
andprop()
as thing change with DOM output withprop()
as full link fromorigin
andBoolean
value for checkbox(pre-1.6)
We can only access DOM elements with
prop
other then it givesundefined
如果以这种方式编写代码,Gary Hole 的回答对于解决问题非常相关
由于 prop 函数返回
CSSStyleDeclaration
对象,上述代码在某些浏览器中将无法正常工作(使用IE8 进行测试)在我的例子中是 Chrome 框架插件
)。因此将其更改为以下代码
解决了问题。
Gary Hole answer is very relevant to solve the problem if the code is written in such way
Since the prop function return
CSSStyleDeclaration
object, above code will not working properly in some browser(tested withIE8 with Chrome Frame Plugin
in my case).Thus changing it into following code
solved the problem.