所以jQuery 1.6有新功能 prop()
.
$(selector).click(function(){
//instead of:
this.getAttribute('style');
//do i use:
$(this).prop('style');
//or:
$(this).attr('style');
})
或者在这种情况下他们做同样的事情吗?
如果我必须改用
prop()
, 所有旧的attr()
如果我切换到 1.6,通话会中断吗?更新
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>
(另见这个 fiddle :http://jsfiddle.net/maniator/JpUF2/)
控制台记录
getAttribute
作为字符串,attr
作为字符串,但 prop
作为 CSSStyleDeclaration
, 为什么?这对我 future 的编码有何影响?
最佳答案
2012 年 11 月 1 日更新
我原来的答案专门适用于 jQuery 1.6。我的建议保持不变,但 jQuery 1.6.1 稍微改变了一些事情:面对预测的一堆损坏的网站,jQuery 团队 reverted attr()
to something close to (but not exactly the same as) its old behaviour for Boolean attributes . John Resig 也 blogged about it .我可以看到他们遇到的困难,但仍然不同意他更喜欢 attr()
的建议。 .
原答案
如果您只使用过 jQuery 而不是直接使用 DOM,这可能是一个令人困惑的变化,尽管它在概念上绝对是一个改进。但是对于使用 jQuery 的无数网站来说并不是那么好,这些网站会因为这种变化而崩溃。
我将总结主要问题:
prop()
而不是 attr()
. prop()
做什么attr()
以前做。替换对 attr()
的调用与 prop()
在您的代码中通常会起作用。 checked
属性是 bool 值,style
property 是一个对象,每个样式都有单独的属性,size
属性是一个数字。 value
和 checked
:对于这些属性,属性始终表示当前状态,而属性(旧版本的 IE 除外)对应于输入的默认值/检查状态(反射(reflect)在 defaultValue
/defaultChecked
属性中)。 如果您是 jQuery 开发人员并且对属性和属性的整个业务感到困惑,那么您需要退后一步并了解一点,因为 jQuery 不再努力保护您免受这些东西的影响。对于该主题的权威但有些干巴巴的词,有规范:DOM4 , HTML DOM , DOM Level 2 , DOM Level 3 . Mozilla 的 DOM 文档适用于大多数现代浏览器,并且比规范更易于阅读,因此您可以找到它们的 DOM reference有帮助。有一个section on element properties .
作为属性比属性更容易处理的一个例子,考虑一个最初选中的复选框。以下是两个可能的有效 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
做的最简单的事情。 bool 属性,自 1995 年以来在每个主要的可脚本浏览器中都存在并完美运行:if (document.getElementById("cb").checked) {...}
该属性还使选中或取消选中复选框变得微不足道:
document.getElementById("cb").checked = false
在 jQuery 1.6 中,这明确地变成
$("#cb").prop("checked", false)
使用
checked
的想法为复选框编写脚本的属性是无用且不必要的。该属性(property)是您所需要的。checked
来选中或取消选中复选框的正确方法并不明显。属性 关于javascript - .prop() 与 .attr(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58290314/