jQuery学习二-添加删除元素

来源:互联网 发布:python hexdump 编辑:程序博客网 时间:2024/06/15 06:00

jQuery的添加元素主要有4个方法
1. appened() //在被选中的元素结尾添加(被选中的元素内)
2. prepend() //在被选中的元素开头添加(被选中的元素内)
3. before()//在被选中的元素前添加(被选中的元素外)
4. after()//在被选中的元素后添加(被选中的元素外)
上面的几个方法除了能添加元素外,还能添加html , jQuery , DOM(也就是js)

下面是简单的实现代码:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>test</title>    <script src="jquery-3.2.1.min.js"></script>    <script src="test.js"></script>    <!--<link type="text/css" rel="stylesheet" href="test.css">--></head><body>    <p id="p1">hello world</p>    <p id="p2">hello world</p>    <p id="p3">hello world</p>    <p id="p4">hello world</p>    <button id="btn1">append</button>    <button id="btn2">prepend</button>    <button id="btn3">before</button>    <button id="btn4">after</button>    <button onclick="appendText()">添加其它</button></body></html>

js:

$(document).ready(function () {    $("#btn1").click(function () {//元素内原文本后添加        $("#p1").append(" test succeess");    });    $("#btn2").click(function () { //元素内原文本前添加        $("#p2").prepend(" test succeess");    });    $("#btn3").click(function () {  //元素前面添加        $("#p3").before(" test success");    });    $("#btn4").click(function () {  //元素后面添加        $("#p4").after(" test success");    });});function appendText() {    var text1 = "<p>test success</p>";     //html    var text2 = $("<P></P>").text("test success");     //jquery    var text3 = document.createElement("p");      //DOM    text3.innerHTML="test success";    $("body").append(text1,text2,text3);}

通过上面的代码就能实现了简单的元素的添加,上面有添加其它html,jq,dom 只是简单用了append来进行实现,你也可以用其它的三个方法。

既然有了添加,当然也有删除了,删除主要有二个方法分别是remove()和empty()。
它们的区别在于,remove()是删除所有元素,而empty()只是删除被选中元素的子元素,remove()是带被选中的元素都删掉。

下面用代码实现一下。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Del</title>    <script src="jquery-3.2.1.min.js"></script>    <script src="del.js"></script></head><body>    <div  id="div" style="width: 200px; height: 200px; background-color: blue; border: solid black">        <p>test</p>        <p>hello world</p>        <p>hahahaha</p>    </div>    <button id="btn">remove</button>    <div  id="div1" style="width: 200px; height: 200px; background-color: blue; border: solid black">        <p>test</p>        <p>hello world</p>        <p>hahahaha</p>    </div>    <button id="btn1">empty</button></body></html>

js

$(document).ready(function () {    $("#btn").click(function () {        $("#div").remove();//删除全部    });    $("#btn1").click(function () {        $("#div1").empty();//删除子元素    });});