首页 > jquery 的 prop() 和 attr() 有什么区别?

jquery 的 prop() 和 attr() 有什么区别?

attr() 的解释

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

prop() 的解释

Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.

几乎看不出二者的区别啊?


Google了一下题主的问题就找到了几个答案
直接贴前三个上来
jQuery 中attr() 和prop() 方法的区别—— 文翼的博客
javascript - .prop() vs .attr() - Stack Overflow
jQuery的attr与prop - dolphinX - 博客园
希望对题主有用


attribute是HTML中定义的,properties是DOM中定义的。
大部分attribute和property是对应的,但有些例外,比如value attribute是初始值,value property是当前值。


http://lmgtfy.com/?q=jquery+prop+attr+%E5%8C%BA%E5%88%AB

:)


首先,attr和prop不能单独看,他们是有前提的,前提是一个JQ对象。

假如页面中有一个<div class="main"></div>

$('.main').attr()是读取$('.main')这个JQ对象中的attribute
$('.main').prop()是读取$('.main')这个JQ对象中得property

任意一个DOM节点(例如一个<div>),他拥有很多HTML的attribute属性,有自带的例如class="header",也有用户自定义的custom="system-header"

同时,任意一个DOM节点,本身也是一个JS对象,而JS对象,就有property属性。

所以,可以通俗的理解为,attr()是读取html上面的属性、prop()是读取JS对象上面的属性。

attribute和property的同步机制略微复杂,一般不用考虑,除非是做表单控件。

详细内容可以看这个
https://www.mxgw.info/coding/javascript-attribute-property.html

【热门文章】
【热门文章】