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.
獲取匹配的元素集合中第一個元素的集合中第一個元素個選定的元素加入一個至多個attribute
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 elatched.中第一個元素的property,或是為每個選定的元素添加一個至多個property
可以觀察到,兩者之間的功能是十分相近的,只是兩者操作的對像不同。
這樣,我們將問題縮小為attribute與property之間的差異。
先說attribute
節點的屬性值,我們指的是中的src的值
<img id='test' src='test.jpg' alt="jQuery:attr()與prop()的差別" > <script type='text/javascript'> var image = document.getElementById('test'); console.log(image.getAttribute('src')); </script>
<img id='test' src='test.jpg' alt="jQuery:attr()與prop()的差別" > <script type='text/javascript'> var image = document.getElementById('test'); image.setAttribute('src', 'another.jpg'); </script>
attr()的功能便是結合javascript中的getAttribute()與setAttribut(),操作的物件是節點的屬性值。
再說property
<img id='test' src='test.jpg' alt="jQuery:attr()與prop()的差別" > <script type='text/javascript'> var image = document.getElementById('test'); console.log(image.src); </script>
再看看設定DOM元素特性值:
<img id='test' src='test.jpg' alt="jQuery:attr()與prop()的差別" > <script type='text/javascript'> var image = document.getElementById('test'); image.src='another.jpg'; </script>
<img id='test' src='test.jpg' alt="jQuery:attr()與prop()的差別" > <script type='text/javascript'> var image = document.getElementById('test'); image.src='another.jpg'; console.log(img.getAttribute('src')); </script>