Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - .prop()与.attr()(.prop() vs .attr())

So jQuery 1.6 has 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 do have to switch to using prop() , all the old attr() calls will break if i switch to 1.6?

(如果我确实必须切换到使用prop() ,那么如果我切换到1.6,所有旧的attr()调用都会中断?)

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 getAttribute as a string, and the attr as a string, but the prop as a CSSStyleDeclaration , Why?

(控制台将getAttribute作为字符串记录,将attr作为字符串记录,但将prop作为CSSStyleDeclaration ,为什么?)

And how does that affect my coding in the future?

(将来如何影响我的编码?)

  ask by Neal translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update 1 November 2012

(2012年11月1日更新)

My original answer applies specifically to jQuery 1.6.

(我的原始答案专门适用于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 .

(我的建议保持不变,但jQuery 1.6.1进行了一些细微更改:面对预期的一堆破损网站,jQuery团队将attr()恢复为接近(但不完全相同)的布尔属性旧行为。 。)

John Resig also blogged about it .

(约翰·雷西格(John Resig)也对此发表了博客 。)

I can see the difficulty they were in but still disagree with his recommendation to prefer attr() .

(我可以看到他们遇到的困难,但仍然不同意他对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.

(如果您只使用过jQuery,而没有直接使用过DOM,则这可能是一个令人困惑的更改,尽管从概念上来说这绝对是一种改进。)

Not so good for the bazillions of sites using jQuery that will break as a result of this change though.

(对于使用jQuery的成千上万的网站来说,效果不是很好,但是由于此更改,这些网站将中断。)

I'll summarize the main issues:

(我将总结主要问题:)

  • You usually want prop() rather than attr() .

    (您通常需要prop()而不是attr() 。)

  • In the majority of cases, prop() does what attr() used to do.

    (在大多数情况下, prop()执行attr()过去的工作。)

    Replacing calls to attr() with prop() in your code will generally work.

    (通常,可以在代码中用prop()替换对attr()调用。)

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

    (例如, checked属性是一个布尔值, style属性是一个对象,每个对象都有各自的属性, size属性是一个数字。)

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

    (当一个属性和一个具有相同名称的属性同时存在时,通常更新一个属性会更新另一个属性,但是对于某些输入属性(例如valuechecked则不是这种情况:对于这些属性,该属性始终表示当前状态而属性(旧版IE中除外)对应于输入的默认值/检查(反映在defaultValue / defaultChecked属性中)。)

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

    (这项更改消除了固定在属性和属性前面的jQuery魔术层,这意味着jQuery开发人员将不得不学习一些有关属性和属性之间差异的知识。)

    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.

(如果您是jQuery开发人员,并且对整个业务都对属性和属性感到困惑,那么您需要退后一步,并对其有所了解,因为jQuery不再那么努力地使您远离这些东西。)

For the authoritative but somewhat dry word on the subject, there's the specs: DOM4 , HTML DOM , DOM Level 2 , DOM Level 3 .

(对于有关该主题的权威性但有些措手不及的单词,有以下规范: DOM4HTML DOMDOM Level 2DOM 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.

(Mozilla的DOM文档对大多数现代浏览器均有效,并且比规范更易于阅读,因此您可能会发现其DOM参考有用。)

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:

(这是有效的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?

(那么,如何确定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:

(实际上,这是世界上最简单的事情:使用checked Boolean属性,自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

(在jQuery 1.6中,这无疑变成了)

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

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

(使用checked属性编写复选框脚本的想法是无益且不必要的。)

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

    (目前尚不清楚使用checked属性检查或取消选中复选框的正确方法是什么)

  • The attribute value reflects the default rather than the current visible state (except in some older versions of IE, thus making things still harder).

    (该属性值反映的是默认值,而不是当前的可见状态(某些IE的较旧版本除外,因此使操作更加困难)。)

    The attribute tells you nothing about the whether the checkbox on the page is checked.

    (该属性不会告诉您是否已选中页面上的复选框。)

    See http://jsfiddle.net/VktA6/49/ .

    (参见http://jsfiddle.net/VktA6/49/ 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...