App下載

jQuery中的prop和attr區(qū)別在哪

猿友 2020-08-03 16:39:59 瀏覽數(shù) (3214)
反饋

JQuery中,對CheckBox的操作分兩個階段,一個是JQuery1.6之前的版本,一個是1.6之后的版本

在1.6之前,我們這么做:

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

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

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

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

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

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

并不是所有的attribute與對應(yīng)的property名字都一致,比如剛才使用的attributeclass屬性,使用property操作的時候應(yīng)該是這樣className t.className='active2';

對于值是true/falseproperty,類似于inputchecked attribute等,attribute取得值是HTML文檔字面量值,property是取得計(jì)算結(jié)果,property改變并不影響attribute字面量,但attribute改變會一向property計(jì)算 <input id="test3" type="checkbox"/>

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

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

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

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

以上就是關(guān)于jQuery中的prop()attr()有什么區(qū)別的相關(guān)知識,希望對大家有所幫助,感興趣的同學(xué)可以看一下教程

jQuery教程:http://www.o2fo.com/jquery/

jQuery微課:http://www.o2fo.com/minicourse/play/jquerycourse

0 人點(diǎn)贊