jQuery中的prop和attr区别在哪

猿友 2020-08-03 16:39:59 浏览数 (2618)
反馈

JQuery中,对CheckBox的操作分两个阶段,一个是JQuery1.6之前的版本,一个是1.6之后的版本

在1.6之前,我们这么做:

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

但是细心的同学会发现,在jQuery1.6之后,如果还像上面这么做,那肯定会出问题: $('#checkbox').attr('checked');获取到的值并不是truefalse,而是checked或者undefined

那在1.6之后如何进行操作呢?

jQuery在之后的版本中对属性和特性进行了比较细致的区分,什么是特性呢? 特性就是像 checkedselectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和defaultSelected等等这些。

那prop()和attr()到底有什么区别呢?

build-in属性,attributeproperty共享数据,attribute更改了会对property造成影响,反之亦然,但是两者的自定义属性是独立的数据,即使name一样,也互不影响,看起来是下面这张图,但是IE6、7没有作区分,依然共享自定义属性数据

并不是所有的attribute与对应的property名字都一致,比如刚才使用的attributeclass属性,使用property操作的时候应该是这样className t.className='active2';

对于值是true/falseproperty,类似于inputchecked attribute等,attribute取得值是HTML文档字面量值,property是取得计算结果,property改变并不影响attribute字面量,但attribute改变会一向property计算 <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

对于一些和路径相关的属性,两者取得值也不尽相同,但是同样attribute取得是字面量,property取得是计算后的完整路径 <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()到底有什么区别

以上就是关于jQuery中的prop()attr()有什么区别的相关知识,希望对大家有所帮助,感兴趣的同学可以看一下教程

jQuery教程:https://www.w3cschool.cn/jquery/

jQuery微课:https://www.w3cschool.cn/minicourse/play/jquerycourse

0 人点赞