jq基本操作

104 阅读1分钟

遍历方法 each( ) :规定为每个匹配元素规定运行的函数 each 回调函数里面的第一个参数表示元素的索引
回调函数里面的第二个参数表示每一个遍历的原生元素❤

     $('li').each(function(i,e){
         console.log(e);
     })
     
     

点击 标题 祝福东奥 把li所有的内容都变成 我要祝福东奥 使用each方法遍历

    $('h1').click(function(){
        $('li').each(function(i,e){
            $(e).text(`我要祝福东奥${i}`)
        })
    })

filter 过滤 在集合元素中过滤出指定的元素

    let lis = $('li').filter('.tt1');
     console.log(lis)
     parent():获取元素的父级元素 
     let f = $('.tt1').parent()
     console.log(f);

parents():返回元素的所有祖先元素

     let fs = $('.tt1').parents();
     console.log(fs);


     $('li').click(function(){
         $(this).css('background','#ccc').siblings().css('background','')
     })
     

用于获取位于匹配元素前面和后面的所有同辈元素 siblings() 除了他自己 前面后面的都被选中了

     let lis = $('.tt1').siblings()
     console.log(lis);

用于获取紧邻匹配元素之后的元素 next() 有多个.tt 会返回一个紧邻匹配元素之后的元素的集合

     let d = $('.tt').next()
    console.log( d );

next prev方法 获取不到元素 会返回jq对象 document 用于获取紧邻匹配元素之前的元素 prev()

     let d = $('.yu').prev()
    console.log( d );

children()方法可以用来获取元素的所有子元素

    let lis = $('ul').children('.tt')
   console.log(lis.length);
   

children获取不到元素会返回jq对象 document

    let c = $('.box').children('.tt')
    

find 可以获取后代的元素

    let c = $('.box').find('span')
     console.log(c);