【发布时间】:2023-04-07 05:12:01
【问题描述】:
所以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,为什么?这对我以后的编码有何影响?
【问题讨论】:
-
这肯定会引起人们的兴趣:books.google.ca/…
-
@Neal,因为这个改变超越了 jQuery。 HTML 属性和 DOM 属性之间的区别是巨大的。
-
看到 jQuery 恢复了更改让我感到难过。他们正朝着错误的方向前进。
-
@尼尔。是的,它只是使问题进一步复杂化,而不是将这两种方法分开。
-
@BritishDeveloper 答案比简单地说明总是使用 x 或 y 更复杂,因为这取决于你想要得到什么。你想要属性,还是想要属性?它们是两种截然不同的东西。
标签: javascript jquery dom attr prop