.prop() V.S. attr.()

prop 是作用在 DOM 元素上 ,而 attr 是作用在 html 文檔上,當我們去取得還未設定的屬性時(ex:checked),用 attr() 時,會傳 undifined ,因為 attr() 只會回傳 string 的型態的資料但是我們沒有設定 checked 這個屬性,而 prop() 則會回傳任何型態的資料,因此在選取未設定的屬性時用 prop()會比較好。

attr prop
定義 HTML的特性 DOM元素的特性
回傳值 字串 任何值

例子

<input type='checkbox' id='test1' checked>
<input type='checkbox' id='test2'>
$('#test1').attr('checked') //print checked
$('#test1').prop('checked') //print true
$('#test2').attr('checked') //print undifined
$('#test2').prop('checked') //print false

參考資料

jQuery .attr() vs .prop()

jQuery 的 attr 与 prop 的区别.