jQuery

作者: chengfengwang | 来源:发表于2017-06-30 18:01 被阅读0次

选取元素

和css选择器几乎一样
$(''),引号里面加入CSS选择器语法就可以

  • 找孩子
$node.children()
$node.children('.children1')
  • 找祖先
//可以查找祖先的某个元素
$node.parents([selector])
  • 选取类数组对象的第某个
    .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();  // 删除元素

获取元素内容

.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') //设置
$node.attr('data-src','logo.png'); //添加自定义属性

获取设置元素宽高

$node.width(); $node.width(200)
$node.height(); $node.height(200)
$node.innerWidth() 包括内边距
$node.outerWidth() 包括内边距包括边框
$node.outerWidth(true) 包括内边距包括边框包括外边距

获取元素坐标

$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))
通常用来遍历普通数组或者对象

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) // 设置为选中或不选中

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

相关文章

网友评论

      本文标题:jQuery

      本文链接:https://www.haomeiwen.com/subject/isxecxtx.html