選取元素
和css選擇器幾乎一樣
$(''),引號里面加入CSS選擇器語法就可以
- 找孩子
$node.children()
$node.children('.children1')
- 找祖先
//可以查找祖先的某個元素
$node.parents([selector])
- 選取類數(shù)組對象的第某個
.eq()
$('li').eq(0).html()
$('li').eq(1).html()
.first() .last()
$('li').first().html()
$('li').last().html()
- 按條件查找元素
.find()
<ul>
<li class='active'>1</li>
<li>2</li>
<li>3</li>
</ul>
$('ul').find('.active').html()
- 排除某個選項
$('.xxx').not('.xx').on('click',function(){})
添加,刪除元素
$ct.prepend($node); // 在容器開頭添加
$ct.append($node); // 在容器末尾添加
$node.remove(); // 刪除元素
獲取元素內(nèi)容
.html() .text()
$('div').html()
$('div').text()
操作CSS
.css()
$('.active').css('display','none')
$('.active').css({
display:'none'
})
添加,刪除class
.addClass() .removeClass()
$('.div1').addClass()
$('.div1').removeClass()
操作屬性
$('img').attr('src') // 獲取
$('img').attr('src','xxx') //設(shè)置
$node.attr('data-src','logo.png'); //添加自定義屬性
獲取設(shè)置元素寬高
$node.width(); $node.width(200)
$node.height(); $node.height(200)
$node.innerWidth() 包括內(nèi)邊距
$node.outerWidth() 包括內(nèi)邊距包括邊框
$node.outerWidth(true) 包括內(nèi)邊距包括邊框包括外邊距
獲取元素坐標(biāo)
$node.offset().left
$node.offset().top
獲取元素索引
$node.index() //node在同輩元素中的索引位置
$('li').index($node) //node在li元素中的索引位置
事件
- 事件代理
//給ul下面所有的li綁定事件
<ul>
<li class='active'>1</li>
<li>2</li>
<li>3</li>
</ul>
$('ul').on('click','li',function(e){
console.log(this)
console.log(e.target.innerText)
})
動畫
.animate( properties [, duration ] [, easing ] [, complete ] )
$('#book').animate({
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 5000, function() {
// Animation complete.
});
遍歷
$(selector).each()
通常用來遍歷JQ的DOM對象
$( "li" ).each(function( index,value) { value是原生DOM對象,this也是原生DOM對象
console.log( index + ": " + $(this).text() );
});
jQuery.each(collection,callback(index,value))
通常用來遍歷普通數(shù)組或者對象
var obj = {
"flammable": "inflammable",
"duh": "no duh"
};
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
表單元素
$('input').eq(0).val //獲取輸入值
$('input').eq(0).attr('checked',false)
$('input').eq(0).attr('checked',true) // 設(shè)置為選中或不選中
extend方法
用法一:
var object1 = {
apple: 0,
banana: {weight: 52, price: 100},
cherry: 97
};
var object2 = {
banana: {price: 200},
durian: 100
};
$.extend(object1, object2); //把object2合并到object1,并修改object2,淺拷貝,返回值是object1
用法二:
var object1 = {
apple: 0,
banana: {weight: 52, price: 100},
cherry: 97
};
var object2 = {
banana: {price: 200},
durian: 100
};
$.extend(true, object1, object2);//把object2合并到object1,并修改object2,深拷貝,返回值是object1
用法三:
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = $.extend({}, defaults, options);
//把options和defaults合并到{},通過setting引用合并后返回的對象不會修改defaults,和options