十二、节点操作

十二、节点操作

12.1 this 触发事件的对象

this在js中表示触发事件的对象。

  • 在jquery中有三个是不需要添加双引号的

    • $(this)

    • $(document)

    • $(window)

1
2
3
4
5
6
7
8
9
// 点击哪个p,让哪个p背景颜色改变
$("p").click(function(){
    // pink 为 rgb(255, 192, 203)
    if($(this).css("background-color") == "rgb(255, 192, 203)"){
        $(this).css("background-color","red");
    }else{
        $(this).css("background-color","pink");
    };   
});

UATcvR.png

12.2 parent()父节点

parent():

父节点 只会选中父元素,不会选中其他祖先元素

1
2
3
4
// 点击哪个p,让它的父节点背景色改变
$("p").click(function(){
    $(this).parent().css("background-color","blue"); 
});

UAThVK.png

12.3 siblings() 兄弟节点

siblings():

兄弟节点(同一个父元素)

1
2
3
4
// 点击哪个p,让它的亲兄弟背景色改变
$("p").click(function(){
    $(this).siblings().css("background-color","blue"); 
});

h3为行内元素

UAT72d.png

12.4 children() 儿子节点

children() :

所有亲儿子节点

1
2
3
4
// 点击哪个div,让它的所有亲儿子背景色改变
$("div").click(function(){
    $(this).children().css("background-color","blue"); 
});

UATqKI.png

12.5 不常用的节点操作

12.5.1 next() 下一个兄弟节点

next() 下一个兄弟节点

1
2
3
4
// 点击哪个div,让它的下一个兄弟背景色改变
$("div").click(function(){
    $(this).next().css("background-color","blue"); 
});

UATOqP.png

12.5.2 nextAll() 后面所有兄弟节点

nextAll() 后面所有兄弟节点

1
2
3
4
// 点击哪个p,让它的后面所有兄弟背景色改变
$("p").click(function(){
    $(this).nextAll().css("background-color","blue"); 
});

UATva8.png

12.5.3 prev() 上一个兄弟节点

prev():

上一个兄弟节点

12.5.4 prevAll() 前面所有兄弟节点

prevAll():

前面所有兄弟节点

12.5.5 parents() 所有祖先节点

parents():

所有祖先节点,也可以传递参数,指定父节点

1
2
3
4
// 点击哪个p,让它的所有所有祖先节点背景色改变
$("p").click(function(){
    $(this).parents().css("background-color","blue"); 
});

UA7iMn.png

12.5.6 find() 所有后代节点

find() :

所有后代节点,可以传递参数,指定儿子节点

()内必须有参数,否则无效

1
2
3
4
5
$("#body").click(function(){
    $(this).find("div").css("background-color","blue"); 
    $(this).find("p").css("background-color","red"); 
    $(this).find("h3").css("background-color","orange"); 
});

UA7VaT.png

12.6 练习:连续打点

12.6.1 分条书写

1
2
3
4
5
6
7
8
9
10
11
12
13
/* 
    要求:
        点击p,让p元素的背景颜色改变        red
        让p元素的兄弟背景色改变             green
        让p元素的父亲背景颜色改变           orange
        让p元素的父亲的兄弟背景颜色改变      blue
*/
$("p").click(function(){
    $(this).css("background-color","red");
    $(this).siblings().css("background-color","green");
    $(this).parent().css("background-color","orange");
    $(this).parent().siblings().css("background-color","blue");
});

UA7Kz9.png

12.6.2 连续打点

1
2
3
4
5
6
$("p").click(function(){
    $(this).css("background-color","red")
    .siblings().css("background-color","green")
    .parent().css("background-color","orange")
    .siblings().css("background-color","blue");
});
点击查看

本文标题:十二、节点操作

文章作者:Mango

发布时间:2020年07月08日 - 22:17:32

最后更新:2020年07月08日 - 22:35:39

原始链接:https://mango185.github.io/post/6a1204b9.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------