1. 程式人生 > >Web前段——jquery操作HTML

Web前段——jquery操作HTML

請自行替換jQuery

jQuery獲取內容和屬性

獲取內容的三個方法

  • text() -設定或者返回所選元素的文字內容
  • html() -設定或返回所選元素的內容(包括HTML標記)
  • val() -設定或返回表單的值

獲取屬性

attr()方法 獲取元素內容和屬性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../jquery-3.3.1.min.js"
></script> <script type="text/javascript" > $(document).ready(function () { $(".one").click(function () { alert("text: "+$(".name").text()); }); $(".two").click(function () { alert("html:"+$(".name").html())
; }); }); </script> </head> <body> <p class="name">this is a test where was <b>B</b></p> <button class="one">顯示文字</button> <button class="two"type="button">顯示html</button> </body> </html>

回撥函式的兩個引數,當前元素的下標一節原始值 .text(function(i,origText){});

jQuery——新增元素

  • append()-在所選元素的結尾插入內容
  • prepend()-在所選元素的開頭插入內容
  • after()-在所選元素的之後插入內容
  • before()-在所選元素之前插入內容

jQuery-刪除

  • remove() -刪除被選元素(及其子元素)
  • empty()-刪除被選元素的子元素
$("div").empty();
$("div")remove(); 

jQuery-CSS類

  • addClass()–新增一個類
  • removeClass()–從被選元素中刪除一個或多個類
  • toggleClass()–對被選元素進行新增/刪除類的操作
  • css()-設定或者返回樣式屬相 設定多個CSS屬性$(“p”).css({ “background-color”:“yellow”, “font-size”:“200%” }); 更多內容請走這扇門——?
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css" rel="stylesheet">
        .color{
            background-color: lightgreen;
            color:red;
        }
    </style>
    <script src="../jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".change").click(function () {
                $("p").toggleClass("color");
            });
        });
    </script>
</head>
<body>
    <p>fdhis</p>
    <p>fhdvsd</p>
    <p>difospo[s</p>
    <button type="button" class="change">跟換CSS屬相</button>
</body>
</html>

— jQuery——尺寸

method describe
width()/height() 設定或返回元素的高度或寬度(不包括內邊距,邊框,外邊距
innerWidth()/innerHeight() 返回元素的寬度或高度(包括內邊距)
outerWidth()/outerHeight() 返回元素的寬度/高度(包括內,外邊距,邊框)