前端(5)jquery

1. jQuery

1.1 什么是jQuery

1.它是轻量级的js库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器 (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)。
2.jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTML documents、events、实现动画效果,并且方便地为网站提供AJAX交互。

1.2 什么是jQuery对象

1.jQuery 对象就是通过jQuery包装DOM对象后产生的对象。
2.jQuery 对象是 jQuery 独有的. 如果一个对象是 jQuery 对象, 那么它就可以使用 jQuery 里的方法: $(“#test”).html();

比如: 
 $("#test").html()   意思是指:获取ID为test的元素内的html代码。
 其中html()是jQuery里的方法 
这段代码等同于用DOM实现代码: document.getElementById(" test ").innerHTML; 

虽然jQuery对象是包装DOM对象后产生的,但是jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法.乱使用会报错

约定:如果获取的是 jQuery 对象, 那么要在变量前面加上$. 
var $variable = jQuery 对象
var variable = DOM 对象

基本语法:$(selector).action()

2. 寻找元素

2.1 选择器

2.1.1 基本选择器

  $("*")  $("#id")   $(".class")  $("element")  $(".class,p,div")
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
	<script src="jquery-3.5.0.js"></script>
</head>

<body>
<div>hello div</div>
<p>hello p</p>
<p id="p1">hello p1</p>
<p class="cp2">hello p2</p>
<script>
	<!-- 1.*:所有标签-->
	//$("*").css("color","red").css("background","yellow"); 
	<!-- 2. 标签名:特定标签-->
	//$("div").css("color","red").css("background","yellow"); 
	<!-- 3. id-->
	//$("#p1").css("color","red").css("background","yellow"); 
	<!-- 4. class-->
	//$(".cp2").css("color","red").css("background","yellow"); 
	<!-- 5.class,p,div:并列-->
	$(".cp2,#p1,div").css("color","red").css("background","yellow"); 
</script>
</body>
</html>

2.1.2层级选择器

   $(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.5.0.js"></script>
</head>

<body>
	<p>hello p0</p>
	<div class="outer"
		<div id="div1">
			<p>hello p1</p>
		</div>
		<p>hello p2</p>
		<div id="div2">
			<p>hello p3</p>
		</div>
	</div>
	<p>hello p4</p>
	<script>
	
	<!--  $("ancestor  descendant"):选择给定的祖先元素的所有后代元素-->
	//$(".outer p").css("color","red").css("background","yellow"); 
	<!-- $("parent>child"): 选择所有指定“parent”元素中指定的child直接子元素-->
	//$(".outer>p").css("color","red").css("background","yellow"); 
	<!--  $("prev+next"): 选择所有紧接在prev元素后的next元素-->
	//$(".outer+p").css("color","red").css("background","yellow"); 
	<!-- $("prev~silblings"):匹配prev元素之后的所有兄弟元素,具有相同的父元素,并匹配过滤 siblings选择器-->
	$("#div1~p").css("color","red").css("background","yellow"); 
	</script>
</body>
</html>

2.1.3 基本筛选器

  $("li:first")  $("li:eq(2)")  $("li:even") $("li:gt(1)")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.5.0.js"></script>
</head>

<body>

	<div id="div1">
	<ul>
		<li>1</li>
		<li>2</li>
		<li>3</li>
		<li>4</li>
	</ul>
	</div>
	<script>
	<!--  $("li:first") 第一个-->
	//$("#div1 li:first").css("color","red").css("background","yellow"); 
	<!--  $("li:last") 最后一个-->
	//$("#div1 li:last").css("color","red").css("background","yellow"); 
	<!--  $("li:eq(2)") 根据索引取-->
	//$("#div1 li:eq(2)").css("color","red").css("background","yellow"); 
	<!-- $("li:even") 所有奇数索引-->
	//$("#div1 li:even").css("color","red").css("background","yellow"); 
	<!-- $("li:gt(1)")  选取 index 值大于指定数字的元素。-->
	//$("#div1 li:gt(0)").css("color","red").css("background","yellow"); 
	<!-- $("li:lt(1)")  选取 index 值小于指定数字的元素。-->
	$("#div1 li:lt(2)").css("color","red").css("background","yellow"); 
	</script>
</body>
</html>

2.1.4 属性选择器

  $('[id="div1"]')   $('["alex="sb"][id]')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.5.0.js"></script>
</head>

<body>

	<div id="div1">
	<p name="p1">hello p1</p>
	<p name="p1" id="test">hello p2</p>
	</div>
	<script>
	<!--  $('[name]') 属性名字-->
	//$("[name]").css("color","red").css("background","yellow"); 
	
	<!--  $('[id="div1"]') 属性值-->
	//$("[name='p1']").css("color","red").css("background","yellow"); 

	<!--  $('["name="p1"][id]') 属性组合-->
	//$("[name='p1'][id]").css("color","red").css("background","yellow"); 
	
	</script>
</body>
</html>

2.1.5 表单选择器

  $("[type='text']")----->$(":text")         注意只适用于input标签

  $("input:checked")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.5.0.js"></script>
</head>

<body>

	<div id="div1">
	<input type="text">
	<input type="button">
	</div>
	<script>
	<!--   $("[type='text']") --$(":text")-->
	//$("[type='button']").css("width","300px");
	//$(":button").css("width","300px");

	</script>
</body>
</html>

2.2 筛选器

2.2.1 过滤筛选器

 $("li").eq(2)  $("li").first()  $("ul li").hasclass("test")

2.2.2 查找筛选器

  $("div").children(".test")    $("div").find(".test")  

  $(".test").next()    $(".test").nextAll()   $(".test").nextUntil()

  $("div").prev()  $("div").prevAll()  $("div").prevUntil()

  $(".test").parent()  $(".test").parents()  $(".test").parentUntil() 

  $("div").siblings()

实例1 菜单切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>left_menu</title>

    <script src="js/jquery-2.2.3.js"></script>
    <script>
          function show(self){
//              console.log($(self).text())
              $(self).next().removeClass("hide")
              $(self).parent().siblings().children(".con").addClass("hide")

          }
    </script>
    <style>
          .menu{
              height: 500px;
              width: 30%;
              background-color: gainsboro;
              float: left;
          }
          .content{
              height: 500px;
              width: 70%;
              background-color: rebeccapurple;
              float: left;
          }
         .title{
             line-height: 50px;
             background-color: #425a66;
             color: forestgreen;}


         .hide{
             display: none;
         }


    </style>
</head>
<body>

<div class="outer">
    <div class="menu">
        <div class="item">
            <div class="title" onclick="show(this);">菜单一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜单二</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜单三</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>

    </div>
    <div class="content"></div>

</div>

</body>
</html>

实例2 tab切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
           function tab(self){
               var index=$(self).attr("xxx")
               $("#"+index).removeClass("hide").siblings().addClass("hide")
               $(self).addClass("current").siblings().removeClass("current")

           }
    </script>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
            width: 60%;
        }
        .menu{
            background-color: #cccccc;
            /*border: 1px solid red;*/
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
        }
        .menu a{
            border-right: 1px solid red;
            padding: 11px;
        }
        .content{
            background-color: tan;
            border: 1px solid green;
            height: 300px;
        }
        .hide{
            display: none;
        }

        .current{
            background-color: darkgray;
            color: yellow;
            border-top: solid 2px rebeccapurple;
        }
    </style>
</head>
<body>
      <div class="tab_outer">
          <ul class="menu">
              <li xxx="c1" class="current" onclick="tab(this);">菜单一</li>
              <li xxx="c2" onclick="tab(this);">菜单二</li>
              <li xxx="c3" onclick="tab(this);">菜单三</li>
          </ul>
          <div class="content">
              <div id="c1">内容一</div>
              <div id="c2" class="hide">内容二</div>
              <div id="c3" class="hide">内容三</div>
          </div>

      </div>
</body>
</html>

3. 操作元素(属性css和文档处理)

3.1 属性操作

$("p").text()    $("p").html()   $(":checkbox").val()

$(".test").attr("alex")   $(".test").attr("alex","sb") 

$(".test").attr("checked","checked")  $(":checkbox").removeAttr("checked")

$(".test").prop("checked",true)

$(".test").addClass("hide")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>tab</title>
<script src="jquery-3.5.0.js"></script>

</head>
<body>
<form>
	<input type="checkbox" , name="test", id='ok'>
</form>
	<p>hello p</p>
	<div id="div">hello div</div>
</body>
<script>

	//获取元素text
	console.log($("p").text());
	//获取元素text
	console.log($("p").html());
	//操作元素属性
	$("p").attr("id","testp");
	console.log($("#testp").text());
	//移除属性
	$("p").removeAttr("id");
	console.log($("#testp").text());
	//操作checkbox
	//$(":checkbox").attr("checked",true);
	//$(":checkbox").attr("checked","checked");
	//prop操作元素属性
	//$(":checkbox").prop("checked", true);
	$(":checkbox").attr("checked","checked");
	//$(":checkbox").removeProp("checked");
	//隐藏元素$(".test").addClass("hide")
	$("#div").addClass("hide")
	
</script>
</html>

实例1 编辑框正反选

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.5.0.js"></script>
    <script>

             function selectall(){

                 $("table :checkbox").prop("checked",true)
             }
             function che(){

                 $("table :checkbox").prop("checked",false)
             }

             function reverse(){


//                 var idlist=$("table :checkbox")
//                 for(var i=0;i<idlist.length;i++){
//                     var element=idlist[i];
//
//                     var ischecked=$(element).prop("checked")
//                     if (ischecked){
//                         $(element).prop("checked",false)
//                     }
//                     else {
//                         $(element).prop("checked",true)
//                     }
//
//                 }



                 $("table :checkbox").each(function(){
                     if ($(this).prop("checked")){
                         $(this).prop("checked",false)
                     }
                     else {
                         $(this).prop("checked",true)
                     }

                 });

//               li=[10,20,30,40]
//             $.each(li,function(i){
//                 console.log(i,x)
//             })
//0
//1
//2
//3

/*                  li=[10,20,30,40]
                 dic={name:"yuan",sex:"male"}
                 $.each(li,function(i,x){
                     console.log(i,x)
                 }) */
//0 10
//1 20
//2 30
//3 40
/* 
                 dic={name:"yuan",sex:"male"}
                 $.each(dic,function(i,x){
                     console.log(i,x)
                 })
                 */
             }
//name yuan
//sex male
    </script>
</head>
<body>

     <button onclick="selectall();">全选</button>
     <button onclick="che();">取消</button>
     <button onclick="reverse();">反选</button>

     <table border="1">
         <tr>
             <td><input type="checkbox"></td>
             <td>111</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>222</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>333</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>444</td>
         </tr>
     </table>



</body>
</html>

实例2 模态对话框

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>批量编辑</title>
<!--<link rel="stylesheet" href="css/mycss.css" />-->
<style>
* {
	margin: 0;
	padding: 0;
}

body {
	font-family: 'Open Sans', sans-serif;
	font-weight: 300;
	line-height: 1.42em;
	color: rebeccapurple;
	background-color: goldenrod;
}

h1 {
	font-size: 3em;
	font-weight: 300;
	line-height: 1em;
	text-align: center;
	color: #4DC3FA;
}

.blue {
	color: #185875;
}

.yellow {
	color: #FFF842;
}

/*!*弹出层罩子*!*/
#full {
	background-color: gray;
	left: 0;
	opacity: 0.7;
	position: absolute;
	top: 0;
	filter: alpha(opacity = 30);
}

.modified {
	background-color: #1F2739;
	border: 3px solid whitesmoke;
	height: 400px;
	left: 50%;
	margin: -200px 0 0 -200px;
	padding: 1px;
	position: fixed;
	/*position:absolute;*/
	top: 50%;
	width: 400px;
	display: none;
}

li {
	list-style: none;
	margin: 20px 0 0 50px;
	color: #FB667A;
}

input[type="text"] {
	padding: 10px;
	border: solid 1px #dcdcdc;
	/*transition: box-shadow 3s, border 3s;*/
}

.iputbutton {
	margin: 60px 0 0 50px;
	color: whitesmoke;
	background-color: #FB667A;
	height: 30px;
	width: 100px;
	border: 1px dashed;
}

.container th h1 {
	font-weight: bold;
	font-size: 1em;
	text-align: left;
	color: #185875;
}

.container td {
	font-weight: normal;
	font-size: 1em;
}

.container {
	width: 80%;
	margin: 0 auto;
}

.container td, .container th {
	padding-bottom: 2%;
	padding-top: 2%;
	padding-left: 2%;
}

/*单数行*/
.container tr:first-child {
	background-color: red;
}

/*偶数行*/
.container tr:not(first-child) {
	background-color: cyan;
}

.container th {
	background-color: #1F2739;
}

.container td:last-child {
	color: #FB667A;
}
/*鼠标进过行*/
.container tr:hover {
	background-color: #464A52;
}
/*鼠标进过列*/
.container td:hover {
	background-color: #FB667A;
	color: #403E10;
	font-weight: bold;
	transform: translate3d(5px, -5px, 0);
}
</style>
<script src="jquery-3.5.0.js"></script>
<script>
            //点击【编辑】显示

$(function () {


    $("table[name=host] tr:gt(0) td:last-child").click(function (event) {

//        $("#full").css({height:"100%",width:"100%"});

        $(".modified").data('current-edit-obj', $(this));

        $(".modified,#full").show();

        var hostname = $(this).siblings("td[name=hostname]").text();
        $(".modified #hostname").val(hostname);
        var ip = $(this).siblings("td[name=ip]").text();
        $(".modified #ip").val(ip);
        var port = $(this).siblings("td[name=port]").text();
        $(".modified #port").val(port);
    });
    //取消编辑
    $(".modified #cancel").bind("click", function () {
        $(".modified,#full").hide();
    });

//    确定修改
    $(".modified #ok").bind("click", function (event) {
        var check_status = true;
        var ths = $(".modified").data('current-edit-obj');
        var hostname = $(".modified #hostname").val().trim();
        var ip = $(".modified #ip").val().trim();
        var port = $(".modified #port").val().trim();
        var port = parseInt(port);
        console.log(port);
        //        端口为空设置为22
        if (isNaN(port)) {
            alert("您没有设置正常的SSH端口号,将采用默认22号端口");
            var port = 22;
        }else if ( port > 65535) {
        //            如果端口不是一个数字 或者端口大于65535
            var check_status = false;
            $(".modified #port").css("border-color","red");
            alert("端口号超过范围!")
        };
        // 主机和ip不能是空
        if ( hostname == ""){
            var check_status = false;
            $(".modified #hostname").css("border-color","red");
        }else if (ip == "") {
            var check_status = false;
            $(".modified #ip").css("border-color","red");
        };
        if (check_status == false){
            return false;
        }else{
            //$(this).css("height","60px")   为什么不用$(this),而用$()
            $(ths).siblings("td[name=hostname]").text(hostname);
            $(ths).siblings("td[name=ip]").text(ip);
            $(ths).siblings("td[name=port]").text(port);
            $(".modified,#full").hide();
        };

    });

});
            
        </script>
</head>
<body>
	<h1>
		<span class="blue"><</span>Homework1<span class="blue">></span> <span
			class="yellow">HostList</span>
	</h1>
	<div id="full">
		<div class="modified">
			<li>主机名:<input id="hostname" type="text" value="" />*
			</li>
			<li>ip地址:<input id="ip" type="text" value="" />*
			</li>
			<li>端口号:<input id="port" type="text" value="" />[0-65535]
			</li>
			<div id="useraction">
				<input class="iputbutton" type="button" name="确定" id="ok" value="确定" />
				<input class="iputbutton" type="button" name="取消" id="cancel"
					value="取消" />
			</div>
		</div>
	</div>
	<table class="container" name="host">
		<tr>
			<th><h1>主机名</h1></th>
			<th><h1>IP地址</h1></th>
			<th><h1>端口</h1></th>
			<th><h1>操作</h1></th>

		</tr>
		<tr>
			<td name="hostname">web01</td>
			<td name="ip">192.168.2.1</td>
			<td name="port">22</td>
			<td>编辑</td>
		</tr>
		<tr>
			<td name="hostname">web02</td>
			<td name="ip">192.168.2.2</td>
			<td name="port">223</td>
			<td>编辑</td>
		</tr>
		<tr>
			<td name="hostname">web03</td>
			<td name="ip">192.168.2.3</td>
			<td name="port">232</td>
			<td>编辑</td>
		</tr>
		<tr>
			<td name="hostname">web04</td>
			<td name="ip">192.168.2.4</td>
			<td name="port">232</td>
			<td>编辑</td>
		</tr>
	</table>


</body>
</html>

3.2 CSS操作

    3.2.1(样式)   css("{color:'red',backgroud:'blue'}") 

    3.2.2(位置)   offset()    position()  scrollTop()  scrollLeft()    

    3.2.3(尺寸)   height()  width()  

实例1 返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>


          window.onscroll=function(){

              var current=$(window).scrollTop();
              console.log(current)
              if (current>100){

                  $(".returnTop").removeClass("hide")
              }
              else {
              $(".returnTop").addClass("hide")
          }
          }


           function returnTop(){
//               $(".div1").scrollTop(0);

               $(window).scrollTop(0)
           }




    </script>
    <style>
        body{
            margin: 0px;
        }
        .returnTop{
            height: 60px;
            width: 100px;
            background-color: darkgray;
            position: fixed;
            right: 0;
            bottom: 0;
            color: greenyellow;
            line-height: 60px;
            text-align: center;
        }
        .div1{
            background-color: orchid;
            font-size: 5px;
            overflow: auto;
            width: 500px;
        }
        .div2{
            background-color: darkcyan;
        }
        .div3{
            background-color: aqua;
        }
        .div{
            height: 300px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
     <div class="div1 div">
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>

     </div>
     <div class="div2 div"></div>
     <div class="div3 div"></div>
     <div class="returnTop hide" onclick="returnTop();">返回顶部</div>
</body>
</html>

实例2 滚动菜单

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>

<style>
.menu {
	position: absolute;
	left: 200px;
	width: 200px;
	top: 48px;
	bottom: 0;
	border: 2px solid red;
	overflow: auto;
}

.menu a {
	display: block;
}

.active {
	background-color: green;
}

.test {
	position: fixed;
	top: 48px;
}
</style>
</head>
<body style="margin: 0;">
	<!-- 顶部 -->
	<div class=top style="height: 48px; background-color: #303a40"></div>

	<!-- 左侧菜单 -->
	<div id="menu" class="menu">
		<!-- 需要通过样式调整为块级标签,各占一行 -->
		<a index=1>用戶管理</a> <a index=2>权限管理</a> <a index=3>菜单1</a> <a index=4>菜单2</a>
	</div>

	<!-- 右侧内容 -->
	<div id="content" class="content" onscroll="Gun()"
		style="position: absolute; left: 420px; right: 200px; width: 780px; top: 48px; bottom: 0; border: 2px solid green; overflow: auto;">
		<!-- overflow: auto: 1.如果内容超过布局范围,则显示滚动条, 2.左侧菜单和顶部固定 -->
		<!-- 操作滚轮:
		$("#content").scrollTop()---获取滚轮的高度
		$("#content").scrollTop(0);---滚动到顶部
		$("#content").scrollTop(200000);---滚动到底部
		$("#content").scrollLeft(0);---滚动到左边
		 -->
		<div id="div1" value=1 style="height: 500px; background-color: red">用户管理</div>
		<div id="div2" value=2 style="height: 800px; background-color: green">权限管理</div>
		<div id="div3" value=3 style="height: 1000px; background-color: blue">测试1</div>
		<div id="div4" value=4 style="height: 700px; background-color: yellow">测试2</div>
	</div>
	<div onclick="goTop()" style="cursor:pointer;position: fixed; right: 0; bottom: 0; background-color: green">返回顶部</div>
	
	<script src="jquery-3.5.0.js"></script>


	<script>
		<!-- 操作内容滚轮 -->

		function Gun(){
			var scrollTop = $(".content").scrollTop();
			var top = $(".top").height();
			if(scrollTop>top){
				$("#menu").addClass("test");
			}else{
				$("#menu").removeClass("test");
				$("#menu a").removeClass("active");
			}
			
			<!-- 左侧菜单与右侧内容关联 -->
			<!-- 获取标签距离文档顶部的高度 -->
			<!-- $(...).offset().top		{top: 550, left: 422}  -->
			<!-- 获取标签自己的高度 : $("#div2").height()-->
			<!-- 获取标签内部高度(包含补白,不包含边框):自己高度+padding --  $("#div2").innerHeight()-->
			<!-- 获取标签内部高度(默认包含补白,边框): 自己高度+padding+border -- $("#div2").outerHeight(参数), 如果参数设置为true时才会将边距(margin)计算在内-->
			
			$("#content").children().each(function (){
				var eleTop = $(this).offset().top;
				//var winTop = eleTop - scrollTop;
				//var winBottomTop = eleTop + $(this).height() - scrollTop;
				//winTop<=0 && winBottomTop>0
				if(eleTop<=top){
					//当前内容对应的菜单应该被选中
					var value = $(this).attr("value");
					var temp = "[index=" + value + "]";
					$(temp).addClass("active").siblings().removeClass("active");
					return;
					}
				})

		}
		
		function goTop(){
			$("#content").scrollTop(0);
		}

	</script>

</body>
</html>


3.3 文档处理

  内部插入  $("#c1").append("<b>hello</b>")     $("p").appendTo("div")

               prepend()    prependTo()

  外部插入  before()  insertBefore()  after insertAfter()

                 replaceWith()   remove()  empty()  clone()

clone实例1

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="jquery-3.5.0.js"></script>
</head>
<body>

<!-- 	<p>hello p</p>
	<p>hello p4</p>
	<div id="div">
		<p>hello p1</p>
	</div>
	
	内部插入标签
	<script>
	/* 添加到最后:append */
	//$("#div").append("<p>hello p</p>");
	/* 添加到最后:appendTo */
	//var ele = $("p");
	//ele.appendTo($("#div"));
	/* 添加到前面:prepend */
	//$("#div").prepend("<p>hello p2</p>");
	/* 添加到前面:prependTo */
	//var ele = $("p");
	//ele.prependTo($("#div"));
	</script>
 -->
	<!-- 外部插入标签 -->
	<div id="outer">
		<div class="item">
			<input type="button" value="+" onclick="test(this)">
			<input type="text">
		</div>
	</div>
	
	<script>
	function test(self){
		if($(self).val()=="-"){
			var ele = $(self).parent();
			//remove():删除本身元素
			ele.remove();
			//empty():清空子元素,保留自身元素
		}else{
			var ele = $(self).parent().clone();
			ele.children(":button").val("-");
			ele.appendTo($("#outer"));
		}
		
	}
	</script>
	
	
</body>
</html>

clone实例2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
            <div class="outer">
                <div class="condition">

                        <div class="icons" style="display:inline-block">
                            <a onclick="add(this);"><button>+</button></a>
                        </div>

                        <div class="input" style="display:inline-block">
                            <input type="checkbox">
                            <input type="text" value="alex">
                        </div>
                </div>
            </div>

<script src="jquery-3.5.0.js"></script>
    <script>

            function add(self){
                var $duplicate = $(self).parent().parent().clone();
                $duplicate.find('a[οnclick="add(this);"]').attr('onclick',"removed(this)").children("").text("-");
                $duplicate.appendTo($(self).parent().parent().parent());

            }
           function removed(self){

               $(self).parent().parent().remove()

           }

    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值