jquery prop方法的使用以及与attr方法的区别

对着背影说爱祢 提交于 2019-12-05 19:52:50

prop方法的概况:

prop()是jquery1.6中新加了一个方法,用来区分attr方法,专门用来处理DOM属性。一些内置属性的DOM元素或window对象,如果试图将删除该属性,浏览器可能会产生错误,而prop方法则可以避免这种错误发生。换言之,prop可以说是为了处理DOM属性(如 selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected)而产生的。

 

prop的用法:

返回属性的值:

$(selector).prop(property)



// EXP

<input type=‘checkbox’>

<button>查看</button>

<script>

     $(“button”).click(function(){

          $(“input”).prop(‘checked’);

     });

      //input选中点“查看”返回true

      //input未选中点“查看”返回false   

</script>

设置属性和值:

$(selector).prop(property,value)



// EXP

<input type=‘checkbox’>

<button>选中</button>

<script>

     $(“button”).click(function(){

          $(“input”).prop(‘checked’, true);

     });

</script>

使用函数设置属性和值:

$(selector).prop(property,function(index,currentvalue))



// EXP

<input type="checkbox" name="issac">

<input type="checkbox" name="issac">

<input type="checkbox" name="issac">

<input type="checkbox" name="issac">



<button class="invert-checked">反选</button>



<script type="text/javascript">

    $(".invert-checked").click(function(){

        $("input").prop('checked', function(index,oldValue){

            return !oldValue;

        });

    });

</script>

设置多个属性和值:

$(selector).prop({property:value, property:value,...})



<input type="checkbox” disabled=“disabled" name="issac">



<button class="setProps”>设置多个属性</button>



<script type="text/javascript">

    $(".setProps").click(function(){

        $("input").prop({

            ‘checked': false,

            ‘disabled': false

        });

    });

</script>

 

prop方法的总结:    

     prop方法和attr方法都可以以上面四种方式调用,但是prop方法比attr方法更优的是可以更加好地处理DOM属性;

 

prop与attire相似,那什么时候该用prop?

 

以下是官方建议attr(),prop()的使用:

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

 

以下是个人建议:

  • 对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
  • 对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。

 

再举一个例子:

<input id="chk1" type="checkbox" />是否可见
<input id="chk2" type="checkbox" checked="checked" />是否可见

像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果。

$("#chk1").prop("checked") == false
$("#chk2").prop("checked") == true

如果上面使用attr方法,则会出现:

$("#chk1").attr("checked") == undefined
$("#chk2").attr("checked") == "checked"

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!