jQuery常用属性方法大全 attr(),val()

@@@@属性篇:

写作本篇文章的意义:jQuery的教程千千万,却没有英文版的API讲的系统、到位,一些话用中文翻译过来味道就变了,所以我将英文版的API的一些常用的方法单独提出来放在这里,并用自己的实践+理解陈述,在大家懒得查看官网的时候可以做为参考。

属性的作用的原文描述:These methods get and set DOM attributes of elements.即用来获取/设置DOM元素的属性的值;我们经常需要在页面中从元素中取值和设值,这些方法使用频次“非常高”!所以掌握它是成为牛逼工程师必须的基本功啦!

 

|||||| .addClass()

Description: Adds the specified class(es) to each element in the set of matched elements.

添加指定的类到匹配元素集合中的每一个元素。

1、.addClass(className)

类型:String

一个或多个类(用空格隔开)添加到匹配的元素的class属性。

2、.addClass(function)

类型:Function(Integer index , String currentClassName)==>String

一个函数返回一个或多个空格分隔的类名称添加到现有的类名(s)。 接收元素的索引位置的设置和现有的类名(s)作为参数。 在函数内this是指当前元素的集合。 
3、examples:
①一次添加多个类:
$("p").addClass("myClass  yourClass");

②切换元素的类从一个到另一个:

$("p").removeClass("myClass noClass").addClass("yourClass");

所有p段落中的myClass和noClass都被移除,yourClass则被加入到所有匹配的p元素中。

③接收一个function函数:

$("ul li").addClass(function( index ){
       return "item-"+index;  
})

如果给定无序列表中的两个<li>元素,那么上面的函数的作用是将在第一个<li>中加入item-0类,第二个<li>中加入item-1类。

 

|||||| .attr()

Description:Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

获取匹配元素集合的属性的第一个元素的值,或者设置一个或多个属性给匹配的每个元素。

.attr(attributeName);//只获取匹配元素集合的第一个元素的属性值,想要获取多个值可以利用jQuery的.each()或.map()方法

.attr(attributeName,value);//给制定的属性设置值

①获取属性值:

<body>
<input id="check1" checked="checked" type="checkbox" />
<label for="check1" >check me</label>

<script>
$("input").change(function(){
var $input=$("input[id='check1']");
$("p").html("通过.attr('checked')获取checked的值:"+$input.attr("checked")+<br>
"通过.prop('checked')获取checked的属性值:"+$input.prop("checked")+<br>
"通过.is(':checked')获取checked的属性值:"+$input.is(":checked")+<br>
}
</script>
</body>

结果: Check me

.attr( 'checked' ): checked//取值
.prop( 'checked' ): true//判断
.is( ':checked' ): true//判断

 

上面针对checkbox的情况,相对比较特殊,.attr()是取得属性的值,.prop()在checked, selected,  disabled三个DOM元素属性取值时,返回的结果是布尔型,其他情况下都是返回属性值。

示例:

  <style>
  em {
    color: blue;
    font-weight: bold;
  }
  div {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 <p>Once there was a <em title="huge, gigantic">large</em> dinosaur...</p>
 The title of the emphasis is:<div></div>
 <script>
var title = $( "em" ).attr( "title" );
//var title=$("em").prop("title");与.attr()效果一样
$( "div" ).text( title );
</script>

 

当设置checkbox的选中情况时:

 

 <body>
  
   <input type="checkbox" checked="checked">
  <input type="checkbox">
   <input type="checkbox">
  <input type="checkbox" checked="checked">
 
 <script>
 $( "input[type='checkbox']" ).attr("checked",false);
$("input[type='checkbox']").prop("checked",false);//与.attr()效果一样
 </script>
  
 </body>

 

  

②设置属性值:

.attr(attributeName,value):这种方法设置属性值非常方便,且看:

<img id="greatPhoto" src="1.jsp" alt="this is a photo" />
<script>
$("#greatPhoto").attr("alt","come form my world!");
</script>

设置多个属性值:

$( "#greatPhoto" ).attr({
  alt: "Beijing Brush Seller",
  title: "photo by Kelly Clark"
});

用函数来设置值:

<scirpt>
$("#greatephoto").attr(function( i , val){//获取第i个id值为greatphoto的变量值val,此处的i即是id的索引值,val为其对应的id值
return val+"change";
})
</script>

 

设置id的div基于页面中的位置:

<body>
 
<div>Zero-th <span></span></div>
<div>First <span></span></div>
<div>Second <span></span></div>
 
<script>
$("div").attr("id".function(arr){//设置id的属性值,arr的值即是id属性的值,此处没有用变量i来对应,因为下面用了.each()来循环设置
return arr+"div-id";
}).each(function(){//循环追加信息
$("span",this).html("id='<b>"+this.id+"</b>'");//this指代当前循环的"span"对象
})
</script>
 
</body>

 

 

|||||| .hasClass()

Description: Determine whether any of the matched elements are assigned the given class.

用来判断是否有匹配的类。应用相对比较简单,看例即知:

 <div id="mydiv" class="foo bar"></div>
//判断是否含有类
$( "#mydiv" ).hasClass( "foo" )

  

|||||| .html()

Description: Get the HTML contents of the first element in the set of matched elements.

用来获取匹配的元素集合的第一个元素的文本内容。

<div class="demo-container">
   <div class="demo-box">Demonstration Box</div>
 </div>
 //获取div中的内容
 $( "div.demo-container" ).html();

  

当.html()方法中输入内容时,则会改变对应元素的文本内容。

 

|||||| .removeAttr()

Description: Remove an attribute from each element in the set of matched elements.

清除所有匹配的元素集合的元素。

.removeAttr()方法是从javascript中的.removeAttribute()继承过来,但是jQuery的此方法可以在不同版本的浏览器上运行

.removeAttr(attributeName)需要的类型是String类型:

下面这个例子比较经典,略带一点逻辑:

<button>Change title</button>
<input type="text" title="hello there">
<div id="log"></div>
 
<script>
(function() {
  var inputTitle = $( "input" ).attr( "title" );
  $( "button" ).click(function() {
    var input = $( this ).next();//选择同级元素的下一个元素,也就是下面那个div标签对象
 
    if ( input.attr( "title" ) == inputTitle ) {//如果div对象的title值与input对象的title值相同就清除div对象的title属性值,不相同的情况下则添加input对象的title属性值给div对象
      input.removeAttr( "title" )
    } else {
      input.attr( "title", inputTitle );
    }
 
    $( "#log" ).html( "input title is now " + input.attr( "title" ) );
  });
})();
</script>

 

.removeAttr()与.removeProp()的作用基本相似。

 

|||||| .val()  

Description: Get the current value of the first element in the set of matched elements.

获取匹配元素集合的第一个元素的值。

注意事项:The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

通常用于input、select、textarea。

 

//获取下拉框的foo类中被选中的项的值
$( "select.foo option:selected").val();
 
// 获取所有foo类的下拉框的值
$( "select.foo" ).val();
 
// 获取被选中的复选框的值
$( "input:checkbox:checked" ).val();
 
// 获取被选中的单选按钮的值
$( "input:radio[name=bar]:checked" ).val();

 

下面的例子实现:单选下拉框显示选项的值,多选下拉框显示选中项的值:

<p></p>
 
<select id="single">
  <option>Single</option>
  <option>Single2</option>
</select>
 
<select id="multiple" multiple="multiple">
  <option selected="selected">Multiple</option>
  <option>Multiple2</option>
  <option selected="selected">Multiple3</option>
</select>
 
<script>
function displayVals(){
var singleVal=$("#single").val();
var multipleVals=$("#multiple").val()|| [];//这样写也可以:var multipleVals=$("#multiple").val();
$("p").html(singleVal+"  "+multipleVals.join(","));
}

displayVals();//调用displayVal()方法

$("select").change(displayVals);//当select对象的选项改变时,调用change方法,调用displayVals()方法,如果不加此行,则在变换的时候,不会调用displayVal()这个方法。 
</script>

 从input对象中取值:

<div>
<input type="text" value="some words" />
<p></p>
</div>
<script>
$("input").keyup(function(){
var inputValue=$(this).val();
$("p").text(inputValue);
}).keyup();
</script>

 

||| .val(value)、.val(function)

Description: Set the value of each element  in the set of matched elements.

给匹配元素集合的每一个元素设值。

 

① 点击各个button后将其文本值赋给input对象的文本域:

<div>
<button>Filed1</button>
<button>Filed0</button>
<button>Filed1</button>
<input type="text" />
</div>
<script>
$("button").click(function(){
$("input").val($(this).text());
})
</script>

 ②使用函数声明修改Input对象的值:

<div>
<input type="text" value="do something"/>
<input type="text" value="do something"/>
<input type="text" value="do something"/>
</div>
<script>
$("input").blur(function(){//当Input对象失去焦点的时候,函数开始
$(this).val(function(i,val){//取得第i个input对象的value值
return val.toUpperCase();//把这个值转换成大写
}) ;
})
</script>

 

 至此,所有jQuery的常用属性类方法已经整理完毕。

 

posted @ 2016-09-30 00:53  Bossen  阅读(4950)  评论(0编辑  收藏  举报