jQ-DOM属性的操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box{100px;height:100px;border: solid 2px black;}
    </style>
</head>
<body>
<div class="box" abc="admin">
    <div class="box1">
        <div class="box2">
            <span>hello</span>
            <input type="text" value="123">
        </div>
    </div>
</div>
</body>
<script src="../jquery.js"></script>
<script>
     console.log($("span").parent())     // 直接父级
     console.log($("span").parents())    // 所有父级
     console.log($("span").parentsUntil(".box")) // 指定范围父级,不包括这个父级元素。


    // 原生内容操作对比
    // innerHTML
    // innerText
    // value

    // jq内容操作
     console.log($(".box").html()); //含标签
     console.log($(".box").text());//只是文本
     $(".box").html("<mark>world</mark>") //box里面会多一个mark标签,标签里面写着world
     $(".box").text("<mark>world</mark>")//box里面写着文本<mark>world</mark>
     console.log($("input").val()); //console.log input的默认值
     $("input").val("hello") //设置input的value的值

    // 属性操作
    // addClass见jq第一篇
    // removeClass见jq第一篇

    // css()
     console.log($(".box").css("width"))//一个参数是获取,获取box的宽度

     $(".box").css("width","300px") //两个参数是设置,设置box的宽度

     $(".box").css({
         400,
         height:500,
         background:"red"
     })   //一个对象是批量设置

     console.log($(".box").css(["width","height","border"]));//一个数组是批量获取,获取的也是一个对象:{ "100px", height: "100px", border: "2px solid rgb(0, 0, 0)"}

     var obj = $(".box").css(["width","height","border"])
     $.each(obj,function(key,val){
         console.log(key,val)
     }) //遍历,输出key和val:
//            width 400px
//            height 500px
//            border 2px solid rgb(0, 0, 0)

//     attr(),相当于js中的attribute,可操作内置也可操作非内置
     console.log($(".box").attr("abc")) //一个字符获取
     $(".box").attr("abc","qwe") //两个字符,设置
     $(".box").attr({
         a:10,
         b:20,
         c:30
     }) //一个对象批量设置
     $(".box").removeAttr("b") //删除



</script>
</html>
原文地址:https://www.cnblogs.com/hy96/p/11556141.html