.prop() 与 .attr()

发布于 2024-11-05 07:58:16 字数 1410 浏览 1 评论 0 原文

因此 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,为什么?这对我将来的编码有何影响?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

明月夜 2024-11-12 07:58:16

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 属性是一个数字。
  • 如果属性和同名属性同时存在,通常更新一个属性会更新另一个属性,但对于输入的某些属性(例如 valuechecked:对于这些属性,属性始终表示当前状态,而属性(旧版本的 IE 除外)对应于输入的默认值/检查性(反映在 defaultValue / defaultChecked 属性)。
  • 此更改消除了 jQuery 中属性和属性前面的一些魔法层,这意味着 jQuery 开发人员必须了解一些属性和属性之间的区别。这是一件好事。

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

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

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

那么,如何确定复选框是否已使用 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 属性来检查或取消选中复选框的正确方法并不明显该
  • 属性值反映的是默认值而不是当前的可见状态(除了在某些旧版本的 IE 中,因此使得事情仍然存在)更难)。该属性不会告诉您有关页面上的复选框是否已选中的任何信息。请参阅http://jsfiddle.net/VktA6/49/

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 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/.
兰花执着 2024-11-12 07:58:16

我认为 Tim 说得很好,但让我们退一步:

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

让我们考虑一下 http://example.com/testing.html 页面中的这个锚点:

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

一些无偿的 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"        |  |
|              +−−−−−−−−−−−−−−−−−−−−−−−−−−+  |
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

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

现在,尽管它们是不同的,但由于所有这些都是进化而来的而不是从头开始设计的,因此如果您设置它们,许多属性会写回它们派生的属性。但并非所有人都这样做,正如您从上面的 href 中看到的,映射并不总是直接“传递值”,有时还涉及解释。

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

const link = document.getElementById("fooAnchor");
console.log(link.href);                 // Shows "http://example.com/foo.html"
console.log(link.getAttribute("href")); // Shows "foo.html"

link 对象是真实存在的,您可以看到访问其上的属性 和访问 之间存在真正的区别属性

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

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

这些规范有很好的索引,我建议保留它们的链接;我一直在使用它们。

例如,自定义属性将包括您可能放置在元素上的任何 data-xyz 属性,以便为您的代码提供元数据(现在这在 HTML5 中是有效的,只要您坚持 <代码>数据-前缀)。 (jQuery 的最新版本允许您通过 data 函数访问 data-xyz 元素,但该函数只是 的访问器>data-xyz 属性 [它的作用既多又少];除非您确实需要它的功能,否则我会使用 attr 函数与 data-xyz 交互 。)

属性 attr 函数过去有一些复杂的逻辑来获取他们认为你想要的东西,而不是字面上获取属性。它混淆了概念。转向 propattr 的目的是为了消除它们的混淆。简而言之,在 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, 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:

const link = document.getElementById("fooAnchor");
console.log(link.href);                 // Shows "http://example.com/foo.html"
console.log(link.getAttribute("href")); // Shows "foo.html"

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.

咆哮 2024-11-12 07:58:16

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

为了充分理解它们的工作原理,这里对 HTML 属性和 DOM 属性之间的区别进行了扩展解释。

: HTML 属性

语法:

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

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

var attr;
attr = document.body.getAttribute("class");
//IE 8 Quirks and below
attr = document.body.getAttribute("className");

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

DOM 属性

语法:

document.body.onload = foo;

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

可视化:
DOM Properties

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

文档

示例

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 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:
HTML Attributes
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:
DOM Properties

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

煮酒 2024-11-12 07:58:16

属性位于 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 the className property of that tag in the DOM (That's because class 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 property className 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.

滥情哥ㄟ 2024-11-12 07:58:16

只是 HTML 属性和 DOM 对象之间的区别导致了混淆。对于那些熟悉 DOM 元素本机属性(例如 this.src this.value this.checked 等)的人来说,. prop 是对这个家庭的热烈欢迎。对于其他人来说,这只是增加了一层混乱。让我们澄清一下。

查看 .attr.prop 之间差异的最简单方法是以下示例:

<input blah="hello">
  1. $('input').attr('blah' ):按预期返回 'hello'。这里没有什么惊喜。
  2. $('input').prop('blah'):返回 undefined - 因为它正在尝试执行 [HTMLInputElement] .blah——该 DOM 对象上不存在这样的属性。它仅作为该元素的属性存在于范围内,即 [HTMLInputElement].getAttribute('blah')

现在我们更改一些内容,如下所示:

$('input').attr('blah', 'apple');
$('input').prop('blah', 'pear');
  1. $('input' ).attr('blah'):返回'apple' 嗯?为什么不使用“pear”,因为这是在该元素上最后设置的。因为属性是在输入属性上更改的,而不是 DOM 输入元素本身 - 它们基本上几乎彼此独立工作。
  2. $('input').prop('blah'): returns 'pear'

你真正需要小心的是由于上述原因,请勿在整个应用程序中对同一属性混合使用这些属性

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


.attr vs .prop

第 1 轮:样式

<input style="font:arial;"/>
  • .attr('style') -- 返回匹配的内联样式元素即"font:arial;"
  • .prop('style') -- 返回样式声明对象,即 CSSStyleDeclaration

第二轮:值

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

$('input').prop('value', 'i changed the value');
  • .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 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')

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'

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

<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

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'

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

和我恋爱吧 2024-11-12 07:58:16

TL;DR

在大多数情况下,使用 prop() 而不是 attr()

属性是输入元素的当前状态。 属性是默认值。

属性可以包含不同类型的事物。属性只能包含字符串

TL;DR

Use prop() over attr() 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

只是一片海 2024-11-12 07:58:16

脏检查

这个概念提供了一个可以观察到差异的示例:http://www.w3.org/TR/html5/forms.html#concept-input-checked-dirty

尝试一下:

  • 单击按钮。两个复选框均已选中。
  • 取消选中两个复选框。
  • 再次单击该按钮。仅选中了 prop 复选框。砰!
$('button').on('click', function() {
  $('#attr').attr('checked', 'checked')
  $('#prop').prop('checked', true)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>attr <input id="attr" type="checkbox"></label>
<label>prop <input id="prop" type="checkbox"></label>
<button type="button">Set checked attr and prop.</button>

对于某些属性,例如 button 上的 disabled,添加或删除内容属性 disabled="disabled" 始终会切换属性(在 HTML5 中称为 IDL 属性) )因为 http://www.w3.org/TR/html5 /forms.html#attr-fe-disabled 说:

禁用的 IDL 属性必须反映禁用的内容属性。

所以你可能会逃脱它,尽管它很丑陋,因为它不需要修改 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:

  • click the button. Both checkboxes got checked.
  • uncheck both checkboxes.
  • click the button again. Only the prop checkbox got checked. BANG!

$('button').on('click', function() {
  $('#attr').attr('checked', 'checked')
  $('#prop').prop('checked', true)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>attr <input id="attr" type="checkbox"></label>
<label>prop <input id="prop" type="checkbox"></label>
<button type="button">Set checked attr and prop.</button>

For some attributes like disabled on button, adding or removing the content attribute disabled="disabled" always toggles the property (called IDL attribute in HTML5) because http://www.w3.org/TR/html5/forms.html#attr-fe-disabled says:

The disabled IDL attribute must reflect the disabled content attribute.

so you might get away with it, although it is ugly since it modifies HTML without need.

For other attributes like checked="checked" on input type="checkbox", things break, because once you click on it, it becomes dirty, and then adding or removing the checked="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.

半步萧音过轻尘 2024-11-12 07:58:16

全部内容都在文档中:

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

所以使用道具!

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.

So use prop!

怼怹恏 2024-11-12 07:58:16

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

重要的是,其中许多都是同步的(如果更新 class 属性,html 中的 class 属性也会更新;否则)。 但是某些属性可能会同步到意外的属性 - 例如,属性 checked 对应于属性 defaultChecked< /code>,这样

  • 手动选中复选框将更改 .prop('checked') 值,但不会更改 .attr('checked') .prop('defaultChecked')
  • 设置 $('#input').prop('defaultChecked', true) 也会更改 .attr('checked'),但这在一个元素。

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

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

table with Preferred use


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

  1. .prop() 可以返回任何类型 - 字符串、整数、布尔值;而 .attr() 始终返回一个字符串。
  2. 据说 .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, attribute checked corresponds to property defaultChecked, so that

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

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

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

table with preferred usage


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

  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().
马蹄踏│碎落叶 2024-11-12 07:58:16

.attr()

  • 获取匹配元素集中第一个元素的属性值。
  • 为您提供页面加载时 html 中定义的元素值

.prop()

  • 获取匹配集合中第一个元素的 property 值元素。
  • 给出通过 javascript/jquery 修改的元素的更新值

.attr():

  • Get the value of an attribute for 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

.prop():

  • Get the value of a property for the first element in the set of matched elements.
  • Gives the updated values of elements which is modified via javascript/jquery
冰葑 2024-11-12 07:58:16

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

  1. 获取自定义 HTML 属性(因为它不与 DOM 属性同步)。
  2. 获取与 DOM 属性不同步的 HTML 属性,例如获取标准 HTML 属性的“原始值”,如

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">.
无悔心 2024-11-12 07:58:16

属性 -> HTML

属性 -> DOM

attributes -> HTML

properties -> DOM

孤单情人 2024-11-12 07:58:16

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

美男兮 2024-11-12 07:58:16

.attr() 可以做 .prop() 不能做的一件事:影响 CSS 选择器

这是我在其他答案中没有看到的问题。

CSS 选择器 [name=value]

  • 将响应 .attr('name', 'value')
  • 但并不总是响应 .prop('name', ' value')

.prop() 仅影响少数属性选择器

.attr() 影响所有属性选择器

One thing .attr() can do that .prop() can't: affect CSS selectors

Here's an issue I didn't see in the other answers.

CSS selector [name=value]

  • will respond to .attr('name', 'value')
  • but not always to .prop('name', 'value')

.prop() affects only a few attribute-selectors

.attr() affects all attribute-selectors

素染倾城色 2024-11-12 07:58:16

温馨提示prop()的使用,例如:

if ($("#checkbox1").prop('checked')) {
    isDelete = 1;
} else {
    isDelete = 0;
}

上面的函数用于检查checkbox1是否被选中,如果选中:return 1;如果不是:返回 0。这里使用 prop() 函数作为 GET 函数。

if ($("#checkbox1").prop('checked', true)) {
    isDelete = 1;
} else {
    isDelete = 0;
}

上面的函数用于设置 checkbox1 被选中并始终返回 1。现在函数 prop() 用作 SET 函数。

别搞砸了。

P/S:当我检查图像src属性时。如果src为空,则prop返回页面的当前URL(错误),attr返回空字符串(右)。

Gently reminder about using prop(), example:

if ($("#checkbox1").prop('checked')) {
    isDelete = 1;
} else {
    isDelete = 0;
}

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.

if ($("#checkbox1").prop('checked', true)) {
    isDelete = 1;
} else {
    isDelete = 0;
}

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

生生漫 2024-11-12 07:58:16

prop() 与 attr() 之间还有一些注意事项:

  • selectedIndex、tagName、nodeName、nodeType、ownerDocument、defaultChecked 和 defaultSelected..etc 应使用 .prop() 方法检索和设置。这些没有相应的属性,只是属性。

  • 对于输入类型复选框

     .attr('checked') //返回选中状态
       .prop('checked') //返回 true
       .is(':checked') //返回 true
    
  • 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

       .attr('checked') //returns  checked
       .prop('checked') //returns  true
       .is(':checked') //returns true
    
  • 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().

安静被遗忘 2024-11-12 07:58:16

1) 属性在 DOM 中; HTML 中的一个属性是
解析到 DOM 中。

2) $( elem ).attr( "checked" ) (1.6.1+) "checked" (String) 将
随着复选框状态的变化

3) $( elem ).attr( "checked" ) (1.6 之前) true (布尔值) 已更改
带有复选框状态

  • 我们主要想用于 DOM 对象而不是自定义属性
    例如 data-img, data-xyz

  • 访问 checkbox 值和 href 时也存在一些差异
    随着 DOM 输出的变化,使用 attr()prop()
    prop() 作为来自 origin 的完整链接和复选框的 Boolean
    (1.6 之前)

  • 我们只能使用 prop 访问 DOM 元素,否则它会给出 undefined< /p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>prop demo</title>
  <style>
    p {
      margin: 20px 0 0;
    }
    b {
      color: blue;
    }
  </style>

</head>

<body>

  <input id="check1" type="checkbox" checked="checked">
  <label for="check1">Check me</label>
  <p></p>

  <script>
    $("input").change(function() {
      var $input = $(this);
      $("p").html(
        ".attr( \"checked\" ): <b>" + $input.attr("checked") + "</b><br>" +
        ".prop( \"checked\" ): <b>" + $input.prop("checked") + "</b><br>" +
        ".is( \":checked\" ): <b>" + $input.is(":checked")) + "</b>";
    }).change();
  </script>

</body>

</html>

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

2) $( elem ).attr( "checked" ) (1.6.1+) "checked" (String) Will
change with checkbox state

3) $( elem ).attr( "checked" ) (pre-1.6) true (Boolean) Changed
with checkbox state

  • 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 and href
    with attr() and prop() as thing change with DOM output with
    prop() as full link from origin and Boolean value for checkbox
    (pre-1.6)

  • We can only access DOM elements with prop other then it gives undefined

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>prop demo</title>
  <style>
    p {
      margin: 20px 0 0;
    }
    b {
      color: blue;
    }
  </style>

</head>

<body>

  <input id="check1" type="checkbox" checked="checked">
  <label for="check1">Check me</label>
  <p></p>

  <script>
    $("input").change(function() {
      var $input = $(this);
      $("p").html(
        ".attr( \"checked\" ): <b>" + $input.attr("checked") + "</b><br>" +
        ".prop( \"checked\" ): <b>" + $input.prop("checked") + "</b><br>" +
        ".is( \":checked\" ): <b>" + $input.is(":checked")) + "</b>";
    }).change();
  </script>

</body>

</html>

零時差 2024-11-12 07:58:16

如果以这种方式编写代码,Gary Hole 的回答对于解决问题非常相关

obj.prop("style","border:1px red solid;")

由于 prop 函数返回 CSSStyleDeclaration 对象,上述代码在某些浏览器中将无法正常工作(使用 IE8 进行测试)在我的例子中是 Chrome 框架插件)。

因此将其更改为以下代码

obj.prop("style").cssText = "border:1px red solid;"

解决了问题。

Gary Hole answer is very relevant to solve the problem if the code is written in such way

obj.prop("style","border:1px red solid;")

Since the prop function return CSSStyleDeclaration object, above code will not working properly in some browser(tested with IE8 with Chrome Frame Plugin in my case).

Thus changing it into following code

obj.prop("style").cssText = "border:1px red solid;"

solved the problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文