js------关于JQ中设置属性的方法attr和prop的讲解:setAttribute(name,value) - attr - prop

 方法总结:

官方的建议:
具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop(),
其他的使用 attr() ; 比如设置对应的字体或者背景之类的样式。
原生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");

 

你可能感兴趣的:(Jqery,js)