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的常用屬性類方法已經整理完畢。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM