Javascript .prop() 与 .attr()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5874652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:19:12  来源:igfitidea点击:

.prop() vs .attr()

javascriptjquerydomattrprop

提问by Naftali aka Neal

So jQuery 1.6has the new function prop().

所以jQuery 1.6有了新功能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 dohave to switch to using prop(), all the old attr()calls will break if i switch to 1.6?

如果我有转用prop(),所有的旧attr()电话,如果我切换到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/)

(另见这个小提琴:http: //jsfiddle.net/maniator/JpUF2/

The console logs the getAttributeas a string, and the attras a string, but the propas a CSSStyleDeclaration, Why? And how does that affect my coding in the future?

控制台将 记录getAttribute为字符串,将 记录attr为字符串,但将 记录propCSSStyleDeclaration,为什么?这对我将来的编码有何影响?

采纳答案by Tim Down

Update 1 November 2012

2012 年 11 月 1 日更新

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 prefer attr().

我的原始答案专门适用于 jQuery 1.6。我的建议保持不变,但 jQuery 1.6.1 稍微改变了一些事情:面对预测的一堆损坏的网站,jQuery 团队恢复attr()了一些接近(但不完全相同)其旧行为的 Boolean attributes。John Resig 也写了关于它的博客。我可以看到他们遇到的困难,但仍然不同意他的建议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.

如果您只使用过 jQuery 而不是直接使用 DOM,这可能是一个令人困惑的更改,尽管它在概念上绝对是一个改进。不过,对于使用 jQuery 的无数网站来说并不是那么好,这些网站会因这种变化而中断。

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 checkedproperty is a Boolean, the styleproperty is an object with individual properties for each style, the sizeproperty 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 valueand 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/ defaultCheckedproperty).
  • 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.
  • 你通常想要prop()而不是attr().
  • 在大多数情况下,prop()做什么attr()用的事情。在您的代码中替换对attr()with 的调用prop()通常会起作用。
  • 属性通常比属性更容易处理。属性值只能是字符串,而属性可以是任何类型。例如,checked属性是一个布尔值,style属性是一个对象,每个样式都有单独的属性,size属性是一个数字。
  • 如果一个属性和一个同名的属性都存在,通常更新一个会更新另一个,但对于输入的某些属性,情况并非如此,例如valuechecked:对于这些属性,属性总是代表当前状态,而属性(旧版 IE 除外)对应于输入的默认值/检查性(反映在defaultValue/defaultChecked属性中)。
  • 这一变化消除了一些困在属性和属性前面的神奇 jQuery 层,这意味着 jQuery 开发人员将不得不了解一些关于属性和属性之间的区别的知识。这是一件好事。

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 referencehelpful. There's a section on element properties.

如果您是 jQuery 开发人员,并且对属性和属性的整个业务感到困惑,那么您需要退后一步,了解一下它,因为 jQuery 不再那么努力地保护您免受这些东西的影响。对于这个主题的权威但有些枯燥的词,有规范:DOM4HTML DOMDOM Level 2DOM Level 3。Mozilla 的 DOM 文档适用于大多数现代浏览器,并且比规范更易于阅读,因此您可能会发现他们的DOM 参考很有帮助。有一个关于元素属性部分

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:

作为如何处理属性比处理属性更简单的示例,请考虑最初选中的复选框。这里有两个可能的有效 HTML 片段来执行此操作:

<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:

那么,如何确定复选框是否被 jQuery 选中?查看 Stack Overflow,您通常会发现以下建议:

  • if ( $("#cb").attr("checked") === true ) {...}
  • if ( $("#cb").attr("checked") == "checked" ) {...}
  • if ( $("#cb").is(":checked") ) {...}
  • 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 checkedBoolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:

这实际上是世界上使用checkedBoolean 属性做的最简单的事情,自 1995 年以来,它在每个主要的可编写脚本的浏览器中都存在并完美运行:

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

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

The property also makes checking or unchecking the checkbox trivial:

该属性还使选中或取消选中复选框变得很简单:

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

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

In jQuery 1.6, this unambiguously becomes

在 jQuery 1.6 中,这明确地变成了

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

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

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

使用该checked属性编写复选框脚本的想法是无益和不必要的。物业就是你所需要的。

  • It's not obvious what the correct way to check or uncheck the checkbox is using the checkedattribute
  • 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/.
  • 使用checked属性检查或取消选中复选框的正确方法是什么并不明显
  • 属性值反映的是默认值而不是当前可见状态(除了在一些旧版本的 IE 中,这让事情变得更加困难)。该属性不会告诉您页面上的复选框是否被选中。见http://jsfiddle.net/VktA6/49/

回答by T.J. Crowder

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 propertiesget their initialvalues from attributeswith the same or similar names (valuegets its initial value from the "value" attribute; hrefgets its initial value from the "href" attribute, but it's not exactly the same value; classNamefrom the "class" attribute). Other properties get their initial values in other ways: For instance, the parentNodeproperty gets its value based on what its parent element is; an element always has a styleproperty, whether it has a "style" attribute or not.

DOM 元素是一个对象,是内存中的一个东西。像 OOP 中的大多数对象一样,它具有属性。它还单独具有元素上定义的属性的映射(通常来自浏览器读取以创建元素的标记)。有些元素的属性得到他们最初从值属性具有相同或相似名称(value从“值”属性获取其初始值;href从“href”属性获取其初始值,但它不是完全一样的值;className从“类”属性)。其他属性通过其他方式获取它们的初始值:例如,parentNode属性根据其父元素是什么来获取其值;style属性,无论它是否具有“样式”属性。

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

让我们在页面中考虑这个锚点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):

一些免费的 ASCII 艺术(并遗漏了很多东西):

+???????????????????????????????????????????+
|             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 hrefabove, the mapping is not always a straight "pass the value on", sometimes there's interpretation involved.

现在,虽然它们是不同的,因为所有这些都是进化的,而不是从头开始设计的,如果您设置它们,许多属性会写回它们派生的属性。但并非所有人都这样做,从href上面可以看出,映射并不总是直接的“传递值”,有时会涉及解释。

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

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

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 linkobject is a real thing, and you can see there's a real distinction between accessing a propertyon it, and accessing an attribute.

link物体是一个真实的东西,你可以看到有访问之间的真正的区别属性就可以了,和访问的属性

As Tim said, the vast majorityof 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 hrefand "href" above).

正如蒂姆所说,绝大多数情况下,我们都希望与属性打交道。部分原因是它们的值(甚至它们的名称)在浏览器之间往往更加一致。我们通常只想在没有与之相关的属性(自定义属性)时使用属性,或者当我们知道对于该特定属性时,属性和属性不是 1:1(如href上面的和“href”) .

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

标准属性在各种 DOM 规范中列出:

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-xyzattributes 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-xyzelements via the datafunction, but that function is notjust an accessor for data-xyzattributes [it does both more and less than that]; unless you actually need its features, I'd use the attrfunction to interact with data-xyzattribute.)

例如,自定义属性将包括data-xyz您可能放在元素上以向您的代码提供元数据的任何属性(现在,只要您坚持使用data-前缀,这从 HTML5 开始就有效)。(jQuery的的最新版本给你访问data-xyz通过要素data的功能,但该功能是不是只是一个访问data-xyz属性[它都越来越小于];除非你真正需要它的特点,我会使用的attr功能互动带data-xyz属性。)

The attrfunction 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 propand attrwas meant to de-conflate them. Briefly in v1.6.0 jQuery went too far in that regard, but functionality was quickly added backto attrto handle the common situations where people use attrwhen technically they should use prop.

attr函数曾经有一些复杂的逻辑来获取他们认为你想要的东西,而不是从字面上获取属性。它混淆了这些概念。移动到prop并且attr是为了将它们混为一谈。简要V1.6.0 jQuery的去在这方面太远,但功能迅速添加回attr处理人们使用常见的情况attr时,技术上应该使用prop

回答by T.J. Crowder

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.

jQuery 的这种变化已经发生了很长时间。多年来,他们一直满足于一个名为的函数,该函数attr()主要检索 DOM 属性,而不是您期望从名称中获得的结果。分离attr()prop()应该有助于缓解 HTML 属性和 DOM 属性之间的一些混淆。$.fn.prop()抓取指定的 DOM 属性,同时$.fn.attr()抓取指定的 HTML 属性。

To fully understand how they work, here's an extended explanation on the difference between HTML attributes and DOM properties.:

为了完全理解它们是如何工作的,这里有一个关于 HTML 属性和 DOM 属性之间差异的扩展解释:

HTML Attributes

HTML 属性

Syntax:

句法:

<body onload="foo()">

<body onload="foo()">

Purpose:Allows markup to have data associated with it for events, rendering, and other purposes.

目的:允许标记具有与其关联的数据以用于事件、呈现和其他目的。

Visualization:HTML AttributesThe class attribute is shown here on the body. It's accessible through the following code:

可视化:HTML 属性类属性显示在主体上。可以通过以下代码访问:

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.

属性以字符串形式返回,并且可能因浏览器而异。但是,它们在某些情况下可能至关重要。如上所述,IE 8 Quirks Mode(及以下)需要 get/set/removeAttribute 中的 DOM 属性名称,而不是属性名称。这是了解差异很重要的众多原因之一。

DOM Properties

DOM 属性

Syntax:

句法:

document.body.onload = foo;

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).

目的:允许访问属于元素节点的属性。这些属性类似于属性,但只能通过 JavaScript 访问。这是一个重要的区别,有助于阐明 DOM 属性的作用。请注意,attributes 与 properties 完全不同,因为此事件处理程序分配是无用的并且不会接收事件(body 没有 onload 事件,只有 onload 属性)。

Visualization:DOM Properties

可视化:DOM 属性

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.

在这里,您会注意到 Firebug 中“DOM”选项卡下的属性列表。这些是 DOM 属性。您会立即注意到其中的很多,因为您之前会在不知情的情况下使用它们。它们的值是您将通过 JavaScript 接收到的值。

Documentation

文档

Example

例子

HTML: <textarea id="test" value="foo"></textarea>

HTML: <textarea id="test" value="foo"></textarea>

JavaScript: alert($('#test').attr('value'));

JavaScript: alert($('#test').attr('value'));

In earlier versions of jQuery, this returns an empty string. In 1.6, it returns the proper value, foo.

在早期版本的 jQuery 中,这将返回一个空字符串。在 1.6 中,它返回正确的值,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.

无需查看这两个函数的新代码,我可以自信地说,混淆更多地与 HTML 属性和 DOM 属性之间的差异有关,而不是与代码本身有关。希望这为您解决了一些问题。

-Matt

-马特

回答by yunzen

A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.

属性在 DOM 中;一个属性位于被解析为 DOM 的 HTML 中。

Further detail

更多细节

If you change an attribute, the change will be reflected in the DOM (sometimes with a different name).

如果更改属性,更改将反映在 DOM 中(有时使用不同的名称)。

Example: Changing the classattribute of a tag will change the classNameproperty of that tag in the DOM. If you have no attribute on a tag, you still have the corresponding DOM property with an empty or a default value.

示例:更改class标签的属性将更改该className标签在 DOM 中的属性。如果标签上没有属性,您仍然拥有相应的 DOM 属性,该属性为空值或默认值。

Example: While your tag has no classattribute, the DOM property classNamedoes exist with a empty string value.

示例:虽然您的标签没有class属性,但 DOM 属性className确实存在一个空字符串值。

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.

如果您更改一个,另一个将被控制器更改,反之亦然。这个控制器不是在 jQuery 中,而是在浏览器的本机代码中。

回答by Gary Green

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.srcthis.valuethis.checkedetc, .propis a very warm welcome to the family. For others, it's just an added layer of confusion. Let's clear that up.

导致混淆的只是 HTML 属性和 DOM 对象之间的区别。对于那些习惯于处理 DOM 元素原生属性this.srcthis.valuethis.checked等的人来说,这.prop是一个非常热烈的欢迎家庭。对于其他人来说,这只是增加了一层混乱。让我们把它弄清楚。

The easiest way to see the difference between .attrand .propis the following example:

最简单的方法,看看之间的区别.attr,并.prop为下面的例子:

<input blah="hello">
  1. $('input').attr('blah'): returns 'hello'as expected. No suprises here.
  2. $('input').prop('blah'): returns undefined-- 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')
  1. $('input').attr('blah'):'hello'按预期返回。这里没有惊喜。
  2. $('input').prop('blah'): 返回undefined-- 因为它正在尝试这样做[HTMLInputElement].blah-- 并且该 DOM 对象上不存在这样的属性。它仅作为该元素的属性存在于范围中,即[HTMLInputElement].getAttribute('blah')

Now we change a few things like so:

现在我们像这样改变一些事情:

$('input').attr('blah', 'apple');
$('input').prop('blah', 'pear');
  1. $('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.
  2. $('input').prop('blah'): returns 'pear'
  1. $('input').attr('blah'): 返回是'apple'吗?为什么不“梨”,因为它最后设置在该元素上。因为属性是在 input 属性上更改的,而不是 DOM 输入元素本身——它们基本上彼此独立工作。
  2. $('input').prop('blah'): 返回 '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 applicationfor the above reason.

由于上述原因,您真正需要注意的是不要在整个应用程序中混合使用这些相同的属性

See a fiddle demonstrating the difference:http://jsfiddle.net/garreh/uLQXc/

查看演示差异的小提琴:http : //jsfiddle.net/garreh/uLQXc/



.attrvs .prop:

.attr对比.prop

Round 1: style

第一轮:风格

<input style="font:arial;"/>
  • .attr('style')-- returns inline styles for the matched element i.e. "font:arial;"
  • .prop('style')-- returns an style declaration object i.e. CSSStyleDeclaration
  • .attr('style')-- 返回匹配元素的内联样式,即 "font:arial;"
  • .prop('style')-- 返回一个样式声明对象,即 CSSStyleDeclaration

Round 2: value

第二轮:价值

<input value="hello" type="text"/>   

$('input').prop('value', 'i changed the value');
  • .attr('value')-- returns 'hello'*
  • .prop('value')-- returns 'i changed the value'
  • .attr('value')-- 返回'hello'*
  • .prop('value')-- 返回 'i changed the value'

* Note: jQuery for this reason has a .val()method, which internally is equivalent to .prop('value')

*注:jQuery为此有一个.val()方法,内部等价于.prop('value')

回答by agjmills

TL;DR

TL; 博士

Use prop()over attr()in the majority of cases.

大多数情况下prop()过度使用attr()

A propertyis the current state of the input element. An attributeis the default value.

属性是输入元件的当前状态。一个属性是默认值。

A property can contain things of different types. An attribute can only contain strings

一个属性可以包含不同类型的东西。一个属性只能包含字符串

回答by Arnaud F.

All is in the doc:

一切都在文档中

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

属性和特性之间的差异在特定情况下可能很重要。在 jQuery 1.6 之前,.attr() 方法在检索某些属性时有时会考虑属性值,这可能会导致不一致的行为。从 jQuery 1.6 开始, .prop() 方法提供了一种显式检索属性值的方法,而 .attr() 方法检索属性。

So use prop!

所以使用道具!

回答by lakesare

attributesare in your HTML text document/file(== imagine this is the result of your html markup parsed), whereas
propertiesare in HTML DOM tree(== basically an actual property of some object in JS sense).

属性在你的 HTML文本文档/文件中(== 想象这是你的 html 标记解析的结果),而
属性在 HTML DOM 树中(== 基本上是某个对象在 JS 意义上的实际属性)。

Importantly, many of them are synced (if you update classproperty, classattribute in html will also be updated; and otherwise). Butsome attributes may be synced to unexpected properties - eg, attributecheckedcorresponds to propertydefaultChecked, so that

重要的是,其中许多是同步的(如果您更新class属性,classhtml 中的属性也将更新;否则)。但是有些属性可能会同步到意想不到的属性——例如,attributechecked对应于propertydefaultChecked,这样

  • manually checking a checkbox will change .prop('checked')value, but will not change .attr('checked')and .prop('defaultChecked')values
  • setting $('#input').prop('defaultChecked', true)will also change .attr('checked'), but this will not be visible on an element.
  • 手动检查复选框会改变.prop('checked')值,但不会改变.attr('checked').prop('defaultChecked')
  • 设置$('#input').prop('defaultChecked', true)也会改变.attr('checked'),但这不会在元素上可见。

Rule of thumb is: .prop()method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr()method. (http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/)

经验法则是.prop()方法应该用于布尔属性/属性和 html 中不存在的属性(例如 window.location)。所有其他属性(您可以在 html 中看到的属性)可以并且应该继续使用该.attr()方法进行操作。( http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/)

And here is a table that shows where .prop()is preferred (even though .attr()can still be used).

这是一个表格,显示了.prop()首选的位置(即使.attr()仍然可以使用)。

table with preferred usage

首选用途表



Why would you sometimes want to use .prop() instead of .attr() where latter is officially adviced?

为什么有时要使用 .prop() 而不是 .attr() 后者是官方建议的?

  1. .prop()can return any type - string, integer, boolean; while .attr()always returns a string.
  2. .prop()is said to be about 2.5 times faster than .attr().
  1. .prop()可以返回任何类型——字符串、整数、布尔值;while.attr()总是返回一个字符串。
  2. .prop()据说比 快 2.5 倍.attr()

回答by Kgn-web

.attr():

.attr()

  • Get the value of an attributefor the first element in the set of matched elements.
  • Gives you the value of element as it was defined in the html on page load
  • 获取匹配元素集中第一个元素的属性值。
  • 为您提供页面加载时在 html 中定义的元素值

.prop():

.prop()

  • Get the value of a propertyfor the first element in the set of matched elements.
  • Gives the updated values of elements which is modified via javascript/jquery
  • 获取匹配元素集中第一个元素的属性值。
  • 给出通过 javascript/jquery 修改的元素的更新值

回答by naor

Usually you'll want to use properties. Use attributes only for:

通常你会想要使用属性。仅将属性用于:

  1. Getting a custom HTML attribute (since it's not synced with a DOM property).
  2. Getting a HTML attribute that doesn't sync with a DOM property, e.g. get the "original value" of a standard HTML attribute, like <input value="abc">.
  1. 获取自定义 HTML 属性(因为它未与 DOM 属性同步)。
  2. 获取不与 DOM 属性同步的 HTML 属性,例如获取标准 HTML 属性的“原始值”,例如 <input value="abc">.