首頁(yè)技術(shù)文章正文

Js中prop()和attr()到底有什么區(qū)別?

更新時(shí)間:2020-08-05 來(lái)源:黑馬程序員 瀏覽量:

在JQuery中,對(duì)CheckBox的操作分兩個(gè)階段,一個(gè)是JQuery1.6之前的版本,一個(gè)是1.6之后的版本

在1.6之前,我們這么做:

<input type='checkbox' id='checkbox'/>
<script>
var isChecked = $('#checkbox').attr('checked'); 
$('#checkbox').attr('checked',true); 
</script>


但是細(xì)心的同學(xué)會(huì)發(fā)現(xiàn),在jQuery1.6之后,如果還像上面這么做,那肯定會(huì)出問(wèn)題: $('#checkbox').attr('checked');獲取到的值并不是true和false,而是checked或者undefined。

那在1.6之后如何進(jìn)行操作呢?

jQuery在之后的版本中對(duì)屬性和特性進(jìn)行了比較細(xì)致的區(qū)分,什么是特性呢? 特性就是像 checked,selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和defaultSelected等等這些。

那prop()和attr()到底有什么區(qū)別呢?

1.于build-in屬性,attribute和property共享數(shù)據(jù),attribute更改了會(huì)對(duì)property造成影響,反之亦然,但是兩者的自定義屬性是獨(dú)立的數(shù)據(jù),即使name一樣,也互不影響,看起來(lái)是下面這張圖,但是IE6、7沒(méi)有作區(qū)分,依然共享自定義屬性數(shù)據(jù)


2.并不是所有的attribute與對(duì)應(yīng)的property名字都一致,比如剛才使用的attribute 的class屬性,使用property操作的時(shí)候應(yīng)該是這樣className

t.className='active2';

對(duì)于值是true/false的property,類似于input的checked attribute等,attribute取得值是HTML文檔字面量值,property是取得計(jì)算結(jié)果,property改變并不影響attribute字面量,但attribute改變會(huì)一向property計(jì)算。

var t=document.getElementById('test3');
     console.log(t.getAttribute('checked'));//null
     console.log(t.checked);//false;
     t.setAttribute('checked','checked');
     console.log(t.getAttribute('checked'));//checked
     console.log(t.checked);//true
     t.checked=false;
     console.log(t.getAttribute('checked'));//checked
     console.log(t.checked);//false


4、對(duì)于一些和路徑相關(guān)的屬性,兩者取得值也不盡相同,但是同樣attribute取得是字面量,property取得是計(jì)算后的完整路徑
<a id="test4" href="#">Click</a>

var t=document.getElementById('test4');
 console.log(t.getAttribute('href'));//#
 console.log(t.href);//file:///C:/Users/bsun/Desktop/ss/anonymous.html#

|Attribute/Property|.attr()|.prop()|
|--|--|--|
|accesskey|√| |
|align|√| |
|async|√|√|
|autofocus|√|√|
|checked|√|√|
|class|√| |
|contenteditable|√| |
|draggable|√| |
|href|√| |
|id|√| |
|label|√| |
|location ( i.ewindow.location )|√|√|
|multiple|√|√|
|readOnly|√|√|
|rel|√| |
|selected|√|√|
|src|√| |
|tabindex|√| |
|title|√| |
|type|√| |
|width ( if needed over .width() )|√| |


猜你喜歡:

Javascript中的預(yù)解析是怎么實(shí)現(xiàn)的?

Js實(shí)現(xiàn)深拷貝復(fù)制的方法

Shiro入門(mén)教程:如何實(shí)現(xiàn)身份認(rèn)證?




分享到:
在線咨詢 我要報(bào)名
和我們?cè)诰€交談!