了解了这些才能开始发挥jQuery的威力

2020-05-23 06:15:57易采站长站整理


.prop( propertyName ) 获取元素某特性值


Get the value of a property for the first element in the set of matched elements.



$( elem ).prop( “checked” )


.prop(propertyName,value) / .prop(propertiesJson) / .prop(propertyName,function(index,oldPropertyValue)) 为元素特性赋值


Set one or more properties for the set of matched elements.



$( “input” ).prop( “checked”, true );


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


$( “input[type=’checkbox’]” ).prop({
  disabled: true
});


关于attribute 和 property区别可以看看 jQuery的attr与prop



.data(key,value) / .value(json) 为HTML DOM元素添加数据,HTML5元素 已有data-*属性


Store arbitrary data associated with the matched elements.The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.



$( “body” ).data( “foo”, 52 );
$( “body” ).data( “bar”, { myType: “test”, count: 40 } );
$( “body” ).data( { baz: [ 1, 2, 3 ] } );


.data(key) / .data() 获取获取data设置的数据或者HTML5 data-*属性中的数据


Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.



alert( $( “body” ).data( “foo” ) );
alert( $( “body” ).data() );


alert( $( “body” ).data( “foo” ) ); // undefined
$( “body” ).data( “bar”, “foobar” );
alert( $( “body” ).data( “bar” ) ); // foobar


CSS方法
.hasClass(calssName) 检查元素是否包含某个class,返回true/false


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


$( “#mydiv” ).hasClass( “foo” )


.addClass(className) / .addClass(function(index,currentClass)) 为元素添加class,不是覆盖原class,是追加,也不会检查重复


Adds the specified class(es) to each of the set of matched elements.



$( “p” ).addClass( “myClass yourClass” );


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


removeClass([className]) / ,removeClass(function(index,class)) 移除元素单个/多个/所有class


Remove a single class, multiple classes, or all classes from each element in the set of matched elements.