js------setAttribute(name,value) - attr - prop

 方法總結:

原生js寫法:

setAttribute(name,value)  設置自定義屬性 或 原生屬性
getAttribute(name)   獲取屬性值

var container = document.getElementsByClassName('container');
container.setAttribute('data-text','自定義文本值')
container.getAttribute('data-text') // 自定義文本值
container.dataset.src   // 自定義文本值
1.  attr(name|properties|key,value|fn) 設置或返回被選元素的屬性值。
說明:屬性名                                類型
     name(屬性的名稱)                     String 
     properties(作爲屬性的 名/值對 的對象) Map
     key,value                             String/string
    
     key,function(index, attr)             String,Function
     1:屬性名稱。
     2:返回屬性值的函數,第一個參數爲當前元素的索引值,第二個參數爲原先的屬性值。 

示例:$("img").attr("src");   |  返回文檔中所有圖片的src屬性值
      $("img").attr({ src: "test.jpg", alt: "Test Image" }); |  爲所有圖像設置src和alt屬性。
      $("img").attr("src","test.jpg");  | 爲所有圖片src屬性設置對應的值
      $("img").attr("title", function() { return this.src }); | 把 src屬性的值設置爲title的值

2.prop(name|properties|key,value|fn)  和attr的用法一樣

$("input[type='checkbox']").prop("checked");
$("input[type='checkbox']").prop({disabled: true});
$("input[type='checkbox']").prop("disabled", true);
$("input[type='checkbox']").prop("checked", true);

不過有所區別: attr一般用在設置 標籤非固有屬性上,即非自身攜帶的屬性,獲取時必須標籤上含有該屬性
              prop一般用於標籤的固有屬性上,即自身本身攜帶的屬性,即使標籤上沒有該屬性名

3. removeAttr(name)/removeProp(name)  移除標籤上的對應屬性
$("img").removeAttr("src"); |  $("img").removeProp("src");

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章