jquery 复习笔记-属性

1 key,function(index, attr)

$("img").attr({ src: "test.jpg", alt: "Test Image" });

$("img").attr("src");

2 removeAttr(name)

$("img").removeAttr("src");

3 prop(name|properties|key,value|fn) 获取在匹配的元素集中的第一个元素的属性值。

选中复选框为true,没选中为false

$("input[type='checkbox']").prop("checked");

禁用页面上的所有复选框。

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

禁用和选中所有页面上的复选框。

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

通过函数来设置所有页面上的复选框被选中。

$("input[type='checkbox']").prop("checked", function( i, val ) {
  return !val;
});

4 removeProp(name)  用来删除由.prop()方法设置的属性集

var $para = $("p");
$para.prop("luggageCode", 1234);
$para.append("The secret luggage code is: ", String($para.prop("luggageCode")), ". ");
$para.removeProp("luggageCode");
$para.append("Now the secret luggage code is: ", String($para.prop("luggageCode")), ". ");

5

$("p").addClass("selected");
$("p").addClass("selected1 selected2");

$('ul li:last').addClass(function() {
  return 'item-' + $(this).index();
});

6

从匹配的元素中删除 'selected' 类

$("p").removeClass("selected");

删除匹配元素的所有类

$("p").removeClass();

删除最后一个元素上与前面重复的class

$('li:last').removeClass(function() {
    return $(this).prev().attr('class');
});

7

为匹配的元素切换 'selected' 类

$("p").toggleClass("selected");

每点击三下加上一次 'highlight' 类

var count = 0;
  $("p").click(function(){
      $(this).toggleClass("highlight", count++ % 3 == 0);
  });

根据父元素来设置class属性

$('div.foo').toggleClass(function() {
  if ($(this).parent().is('.bar') {
    return 'happy';
  } else {
    return 'sad';
  }
});