第15/16天,jQuery

简介: @(Web前端)[笔记]jQuery API 3.2.1 速查表目录一、jQuery是什么?二、什么是jQuery对象?三、查找元素(选择器和筛选器) 3.

@(Web前端)[笔记]

jQuery API 3.2.1 速查表

目录

一、jQuery是什么?
二、什么是jQuery对象?
三、查找元素(选择器和筛选器)
    3.1 选择器
        3.1.1 基本选择器
        3.1.2 层级选择器
        3.1.3 基本筛选器
        3.1.4 属性选择器
        3.1.5 表单选择器
    3.2 筛选器
        3.2.1 过滤筛选器
        3.2.2 查找筛选器
四、操作元素
    4.1 事件
        4.1.1 页面载入
        4.1.2 事件绑定
        4.1.3 事件委派
    4.2 属性操作
    4.3 each循环
    4.4 文档节点处理

第16天补充
    4.5 动画效果
        4.5.1 显示与隐藏
        4.5.2 滑动
        4.5.3 淡入淡出
        4.5.4 回调函数
        4.5.5 stop()
    4.6 CSS操作
        4.6.1 位置操作
        4.6.2 尺寸操作
五、jQuery练习
    5.1 table正反选
    5.2 复制样式条
    5.3 注册验证
    5.4 拖动面板
    5.5 轮播图
    5.6 表格编辑

一、jQuery是什么?

[1] jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team。

[2] jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!

[3] 它是轻量级的js库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器

[4] jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTMLdocuments、events、实现动画效果,并且方便地为网站提供AJAX交互。

[5] jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。

二、什么是jQuery对象?

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

jquery的基础语法:$(selector).action()

jQuery语法释译:

$("#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 对象

$variable[0]:jquery对象转为dom对象      $("#msg").html();  转换为DOM方式:$("#msg")[0].innerHTML

三、查找元素(选择器和筛选器)

3.1 选择器

3.1.1 基本选择器

$("") 内和CSS查找标签方式基本保持一致

$("*")              //匹配所有标签
$("#id")            //id选择器
$(".class")         //class类选择器
$("element")        //标签选择器
$(".class,p,div")   //逗号表示“或”的意思,满足其一即可

3.1.2 层级选择器

$(".outer div")     //后代选择器
$(".outer>div")     //子代选择器
$(".outer+div")     //毗邻选择器
$(".outer~div")     //普通兄弟选择器

3.1.3 基本筛选器

$("li:first")       //筛选出第一个li标签
$("li:eq(2)")       //筛选出索引为2的li标签
$("li:even")        //筛选出索引为偶数的li标签
$("li:odd")         //筛选出索引为奇数的li标签
$("li:gt(1)")       //筛选出索引值大于1的li标签

3.1.4 属性选择器

$('[id="div1"]')        //选择有id属性且id="div1"的标签
$('["alex="sb"][id]')   //选择有alex(自定义属性)属性,其值为"sb",并且有id属性的标签

3.1.5 表单选择器

$("[type='text']") 也可以简写为 $(":text")
这种方法只适用于input标签:$("input:checked")

$(":enabled")
$(":disabled")
$(":checked")
$(":selected")

$("input:not(:checked)")  //去除所有与给定选择器匹配的元素

在jQuery 1.3中,已经支持复杂选择器了(例如:not(div a) 和 :not(div,a))

3.2 筛选器

3.2.1 过滤筛选器

$("li").eq(2)       //选择索引值为2的li标签
$("li").first()     //选择第一个li标签
$("ul li").hasClass("test")  //判断所选标签有没有类名为test。

3.2.2 查找筛选器

$("div").children(".test")  //查找子标签
$("div").find(".test")      //查找后代标签

//查找所有兄弟标签
$("div").siblings()         

//向下查找兄弟标签
$(".test").next()           //查找下一个兄弟标签
$(".test").nextAll()        //查找下面所有兄弟标签
$(".test").nextUntil(selector)      //向下查找,截止到符合条件的标签为止


//向上查找兄弟标签
$("div").prev()             //查找上一个兄弟标签
$("div").prevAll()          //查找上面所有兄弟标签
$("div").prevUntil(selector)        //向上查找,截止到符合条件的标签为止 



$(".test").parent()         //查找父标签
$(".test").parents()        //查找所有父级标签
$(".test").parentUntil(selector)    //查找父级标签,截止到符合条件的标签为止       

四、操作元素

4.1 事件

4.1.1 页面载入

ready(fn) 相当于原生JS中的onload事件

ready(fn)  // 当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
$(document).ready(function(){})可以简写为$(function(){}) 

4.1.2 事件绑定

语法:标签对象.事件(函数)
$("p").click(function(){})

4.1.3 事件委派

$("祖先元素").on("事件","后代元素",函数)

$("ul").on("click","li",function(){})

例 :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    //引入jQuery文件
    <script src="../../day15_homework/js/jquery-3.2.1.js"></script>
</head>
<body>
<p><button>添加</button></p>
<ul>
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
    <li>555</li>
</ul>

<script>
    $("button").click(function () {
        $("ul").append("<li>666</li>")
    });

    //不做事件委派
    //$("ul li").click(function () {
    //    $(this).css("color","red")
    //})    

    $("ul").on("click","li",function () {
        $(this).css("color","red")
    })
</script>
</body>
</html>

注意:如果不对li标签做事件委派,那么新添加的li标签就不会绑定对应的事件

4.2 属性操作

属性

//添加或删除类
$("").addClass(class|fn)
$("").removeClass([class|fn])


//属性
$("").attr();
$("").removeAttr();
$("").prop();
$("").removeProp();

注意:

  1. 对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
  2. 对于HTML元素我们自定义的DOM属性,在处理时,使用attr方法。
  3. 像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果。
$("").html()    //括号中加入一个值,是给对象设置内容,可以是文本,也可以是标签。括号为空的话,则是取值。

$("").text()    //获取或设置文本内容

$("").val()     //获取或设置input标签的value值     

添加CSS样式

//一次性设置多个样式
$("#c1").css({"color":"red","fontSize":"35px"})

//设置一个样式
$("#c1").css("color","red")

4.3 each循环

$("p").css("color","red")

以上代码是将css操作加到所有的p标签上,内部维持一个循环;但如果对于选中标签进行不同处理,这时就需要对所有标签数组进行循环遍历啦。

jquery支持两种循环方式:

方式一:

格式:$.each(obj,fn)

li=[10,20,30,40];
dic={name:"yuan",sex:"male"};
$.each(li,function(i,x){
    console.log(i,x)
});

方式二:

格式: $("").each(fn)

$("tr").each(function(){
    console.log($(this).html())
})

注意:其中,$(this)代指当前循环标签。

each扩展

function f(){
    for(var i=0;i<4;i++){
        if (i==2){
            return    //会直接跳出循环
        }
        console.log(i)
    }
}
f();



li=[11,22,33,44];
$.each(li,function(i,v){
    if (v==22){
        return;   //  ===试一试 return false会怎样?
    }
    console.log(v)
});
//function里的return只是结束了当前的函数,并不会影响后面函数的执行.
//本来这样没问题,但因为我们的需求里有很多这样的情况:我们不管循环到第几个函数时,一旦return了,希望后面的函数也不再执行了!

//那就可以这样做:
    // <1>如果你想return后下面循环函数继续执行,那么就直接写return或return true
    // <2>如果你不想return后下面循环函数继续执行,那么就直接写return false

4.4 文档节点处理

//创建一个标签对象
    $("<p>")


//内部插入

    $("").append(content|fn)      ----->$("p").append("<b>Hello</b>"); 在父标签中插入子标签前父后子
    $("").appendTo(content)       ----->$("p").appendTo("div"); 将子标签插入父标签中,前子后父 
    $("").prepend(content|fn)     ----->$("p").prepend("<b>Hello</b>");  与append()相同,不同的是append插入在末尾,prepend插入在开始位置(第一位)。
    $("").prependTo(content)      ----->$("p").prependTo("#foo");

//外部插入

    $("").after(content|fn)       ----->$("p").after("<b>Hello</b>");
    $("").before(content|fn)      ----->$("p").before("<b>Hello</b>");
    $("").insertAfter(content)    ----->$("p").insertAfter("#foo");
    $("").insertBefore(content)   ----->$("p").insertBefore("#foo");

//替换
    $("").replaceWith(content|fn) ----->$("p").replaceWith("<b>Paragraph. </b>");

//删除
    $("").empty()
    $("").remove([expr])

//复制
    $("").clone([Even[,deepEven]])

第16天补充

4.5 动画效果

4.5.1 显示与隐藏

$(selector).show(1000)  //显示,延迟1000毫秒
$(selector).hide(1000)  //隐藏,延迟1000毫秒
$(selector).toggle(1000)    //在显示与隐藏之间切换,延迟1000毫秒

示例:

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

<h1>Hello World</h1>
<button id="show">显示</button>
<button id="hide">隐藏</button>
<button id="qiehuan">切换</button>

<script>
    $("#show").click(function () {
        $("h1").show(1000);   //显示
    });

    $("#hide").click(function () {
        $("h1").hide(1000);   //隐藏
    });

    $("#qiehuan").click(function () {
        $("h1").toggle(1000);  //切换
    })
</script>
</body>
</html>

4.5.2 滑动

$(selector).slideDown(1000);    //滑动出现
$(selector).slideUp(1000);      //滑动隐藏
$(selector).slideToggle(1000);  //滑动切换

示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../day15/day15/jquery/jquery-3.1.1.js"></script>
    <script>
    $(document).ready(function(){
     $("#slideDown").click(function(){
         $("#content").slideDown(1000);   //出现
     });
      $("#slideUp").click(function(){
         $("#content").slideUp(1000);   //隐藏
     });
      $("#slideToggle").click(function(){
         $("#content").slideToggle(1000);  //切换
     })
  });
    </script>
    <style>

        #content{
            text-align: center;
            background-color: lightblue;
            border:solid 1px red;
            display: none;
            padding: 50px;
        }
    </style>
</head>
<body>

    <button id="slideDown">出现</button>
    <button id="slideUp">隐藏</button>
    <button id="slideToggle">toggle</button>

    <div id="content">helloworld</div>

</body>
</html>

4.5.3 淡入淡出

$(selector).fadeIn(1000);       //淡入,延迟1000毫秒
$(selector).fadeOut(1000);      //淡出,延迟1000毫秒
$(selecotr).fadeToggle(1000);   //淡入淡出切换,延迟1000毫秒
$(selector).fadeTo(1000,0.5);   //淡入,延迟1000毫秒,颜色深浅度为0.5

示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../day15/day15/jquery/jquery-3.1.1.js"></script>
    <script>
        $(document).ready(function(){
           $("#in").click(function(){
               $("#id1").fadeIn(1000);    //淡入  
           });
           
            $("#out").click(function(){
               $("#id1").fadeOut(1000);   //淡出
           });
            
            $("#toggle").click(function(){
               $("#id1").fadeToggle(1000);  //切换
           });
            
            $("#fadeto").click(function(){
               $("#id1").fadeTo(1000,0.4);  //淡出,并设置淡出后的颜色深浅度为0.4
           });
        });
    </script>

</head>
<body>
      <button id="in">fadein</button>
      <button id="out">fadeout</button>
      <button id="toggle">fadetoggle</button>
      <button id="fadeto">fadeto</button>
      <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div>
</body>
</html>

4.5.4 回调函数

事件执行完成后,再调用 这个回调函数执行。

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

</head>
<body>
  <button>hide</button>
  <p>helloworld helloworld helloworld</p>
  
 <script>
   $("button").click(function(){
       $("p").hide(1000,function(){
           alert($(this).html())
       })
   })
    </script>
</body>
</html>

4.5.5 stop()

jQuery stop() 方法用于在动画或效果完成前对它们进行停止。

jQuery停止动画


4.6 CSS操作

jQuery 参考手册 - CSS操作

4.6.1 位置操作

**offset() **

获取或设置匹配元素在当前窗口(body标签)的相对偏移,返回的对象包含两个整形属性:top和left,以像素计,此方法只对可见元素有效。

//获取相对偏移量
var $ofs=$(".outer").offset();    //结果是{top:8, left:8}
console.log("上:",$ofs.top);     //获取顶部偏移量
console.log("左:",$ofs.left);      //获取左边偏移量

//设置偏移量
$(".outer").offset({top:50,left:200});  //只能设置顶部和左边,不能设置底部和右边;

offsetParent()

返回最近的定位祖先元素。

$("button").click(function(){
  $("p").offsetParent().css("background-color","red");
});

position()

获取匹配元素相对于已定位的父级元素的偏移。
返回的对象包含两个整形属性:top和left,以像素计。

注: 已定位的父级元素是指设置了绝对定位position:absolute;的父级元素。当所有父级元素没有设置绝对定位时,默认参照body标签取偏移量。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../day15/day15/jquery/jquery-3.1.1.js"></script>
    <style>
        *{
            margin:0;
        }
        .outer{
            width: 500px;
            height: 500px;
            background: #7fff0c;
            margin-top: 50px;
            margin-left: 50px;
            position: absolute;    /*父元素设置绝对定位*/
            top: 0;
            left: 0;
        }
        .title{
            width: 100px;
            height: 100px;
            background: #204982;
        }
    </style>
</head>
<body>
<div class="outer">
    <div class="title"></div>
</div>

<script>
    //获取偏移量
    var $position=$(".title").position();    //结果是{top:0,left:0}
    console.log("上:",$position.top);
    console.log("左:",$position.left);
</script>
</body>
</html>

scrollLeft()scrollTop()

当页面水平方向或垂直方向内容较多,当前窗口无法全部显示,出现滚动条时:

  • scrollLeft() 方法返回或设置匹配元素的滚动条的水平位置。滚动条的水平位置指的是从其左侧滚动过的像素数。当滚动条位于最左侧时,位置是 0。
  • scrollTop() 方法返回或设置匹配元素的滚动条的垂直位置。滚动条的垂直位置是指垂直滚动条相对于其顶部的偏移,以像素计。
$(".btn1").click(function(){
  $("div").scrollLeft(100);   //将水平滚动条定位在距离最左边100像素的位置。

  $("div").scrollTop(100);   //将垂直滚动条定位在距离其顶部100像素的位置。
});

4.6.2 尺寸操作

height([val|fn])
设置或获取盒子元素本身的高度;

width([val|fn])
设置或获取盒子元素本身的宽度;

innerHeight()
获取元素本身的高度加上padding-toppadding-bottom

innerWidth()
获取元素本身的宽度加上padding-leftpadding-right

outerHeight()
元素本身的高度加上padding-toppadding-bottom,再加上边框的上下高度(即border-topborder-bottom

outerWidth()
元素本身的宽度加上padding-leftpadding-right,再加上边框的上下高度(即border-leftborder-right

outerHeight(true)
outerHeight()基础上再加上margin-topmargin-bottom

outerWidth(true)同上

五、jQuery练习

5.1 table正反选

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
     <button>全选</button>
     <button>取消</button>
     <button>反选</button>
     <hr>
     <table border="1">
         <tr>
             <td><input type="checkbox"></td>
             <td>111</td>
             <td>111</td>
             <td>111</td>
             <td>111</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>222</td>
             <td>222</td>
             <td>222</td>
             <td>222</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>333</td>
             <td>333</td>
             <td>333</td>
             <td>333</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>444</td>
             <td>444</td>
             <td>444</td>
             <td>444</td>
         </tr>
     </table><script src="jquery.min.js"></script>
     <script>
            $("button").click(function(){
               if($(this).text()=="全选"){    // $(this)代指当前点击标签
                   $("table :checkbox").prop("checked",true)
               }
                else if($(this).text()=="取消"){
                   $("table :checkbox").prop("checked",false)
               }
                else {
                    $("table :checkbox").each(function(){
                        $(this).prop("checked",!$(this).prop("checked"));
                 });
               }
            });
     </script>
</body>
</html>

5.2 复制样式条

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../day15/day15/jquery/jquery-3.1.1.js"></script>
</head>
<body>
<div class="outer">
    <div class="item">
        <button class="add">+</button>
        <input type="text">
    </div>
</div>

<script>
    $(".add").click(function () {
        var $copy=$(this).parent().clone();
        $copy.children("button").html("-").removeClass("add").addClass("rm");
        $(".outer").append($copy);
    });

    $(".outer").on("click",".rm",function () {
        $(this).parent().remove();
    })
</script>
</body>
</html>

5.3 注册验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../day15/day15/jquery/jquery-3.1.1.js"></script>
</head>
<body>
<form class="Form" id="form">
    <p><input class="v1" type="text" name="username" mark="用户名"></p>
    <p><input class="v1" type="text" name="email" mark="邮箱"></p>
    <p><input type="submit" value="submit"></p>
</form>
<script>
    $("#form :submit").click(function(){
          flag=true;
          $("#form .v1").each(function(){
              $(this).next("span").remove();// 防止对此点击按钮产生多个span标签
              var value=$(this).val();
              if (value.trim().length==0){
                     var mark=$(this).attr("mark");
                     var ele=document.createElement("span");
                     ele.innerHTML=mark+"不能为空!";
                     $(this).after(ele);
                     $(ele).prop("class","error");// DOM对象转换为jquery对象
                     flag=false;
                     return false ; //-------->引出$.each的return false注意点
              }
          });
          return flag
    });
</script>
</body>
</html>

5.4 拖动面板

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="../../day15/day15/jquery/jquery-3.1.1.js"></script>
</head>
<body>
    <div style="border: 1px solid #ddd;width: 600px;position: absolute;">
        <div id="title" style="background-color: black;height: 40px;color: white;">
            标题
        </div>
        <div style="height: 300px;">
            内容
        </div>
    </div>
<script>
    $(function(){
        // 页面加载完成之后自动执行
        $('#title').mouseover(function(){
            $(this).css('cursor','move');
        }).mousedown(function(e){
            //console.log($(this).offset());
            var _event = e || window.event;
            // 原始鼠标横纵坐标位置
            var ord_x = _event.clientX;
            var ord_y = _event.clientY;

            var parent_left = $(this).parent().offset().left;
            var parent_top = $(this).parent().offset().top;

            $(this).on('mousemove', function(e){
                var _new_event = e || window.event;
                var new_x = _new_event.clientX;
                var new_y = _new_event.clientY;

                var x = parent_left + (new_x - ord_x);
                var y = parent_top + (new_y - ord_y);

                $(this).parent().css('left',x+'px');
                $(this).parent().css('top',y+'px');
            })
        }).mouseup(function(){
            $(this).off('mousemove');
        });
    })
</script>
</body>
</html>

5.5 轮播图

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="../../day15/day15/jquery/jquery-3.1.1.js"></script>
    <title>Title</title>
    <style>
        .outer{
            width: 790px;
            height: 340px;
            margin: 80px auto;
            position: relative;
        }
        .img li{
            position: absolute;
            list-style: none;
            top: 0;
            left: 0;
            display: none;
        }
        .num{
            position: absolute;
            bottom: 18px;
            left: 270px;
            list-style: none;
        }
        .num li{
            display: inline-block;
            width: 18px;
            height: 18px;
            background-color: white;
            border-radius: 50%;
            text-align: center;
            line-height: 18px;
            margin-left: 4px;
        }
        .btn{
            position: absolute;
            top:50%;
            width: 30px;
            height: 60px;
            background-color: lightgrey;
            color: white;
            text-align: center;
            line-height: 60px;
            font-size: 30px;
            opacity: 0.7;
            margin-top: -30px;
            display: none;
        }
        
        .left{
            left: 0;
        }
        .right{
            right: 0;
        }
        .outer:hover .btn{
            display: block;
        }
        .num .active{
            background-color: red;
        }
    </style>
</head>
<body>
      <div class="outer">
          <ul class="img">
              <li style="display: block"><a href="">![](img/1.jpg)</a></li>
              <li><a href="">![](img/2.jpg)</a></li>
              <li><a href="">![](img/3.jpg)</a></li>
              <li><a href="">![](img/4.jpg)</a></li>
              <li><a href="">![](img/5.jpg)</a></li>
              <li><a href="">![](img/6.jpg)</a></li>
          </ul>

          <ul class="num">
              <!--通过JS生成-->
              <!--<li class="active"></li>-->
              <!--<li></li>-->
          </ul>

          <div class="left  btn"> < </div>
          <div class="right btn"> > </div>
      </div>
<script>
    var i=0;
//  通过jquery自动创建按钮标签
    var img_num=$(".img li").length;
    for(var j=0;j<img_num;j++){
        $(".num").append("<li></li>")
    }

    $(".num li").eq(0).addClass("active");

// 手动轮播
    $(".num li").mouseover(function () {
        i=$(this).index();
        $(this).addClass("active").siblings().removeClass("active");

        $(".img li").eq(i).stop().fadeIn(200).siblings().stop().fadeOut(200)

    });

// 自动轮播
    var c=setInterval(GO_R,1500);
    function GO_R() {
        if(i==img_num-1){
            i=-1
        }
         i++;
         $(".num li").eq(i).addClass("active").siblings().removeClass("active");
         $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000)
    }

    function GO_L() {
        if(i==0){
            i=img_num
        }
         i--;
         $(".num li").eq(i).addClass("active").siblings().removeClass("active");
         $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);  // fadeIn,fadeOut单独另开启的线程
    }

    $(".outer").hover(function () {
        clearInterval(c)
    },function () {
        c=setInterval(GO_R,1500)
    });

// button 加定播
    $(".right").click(GO_R);
    $(".left").click(GO_L)
</script>
</body>
</html>

5.6 表格编辑

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="bootstrap.min.css">
    <script src="../../day15/day15/jquery/jquery-3.1.1.js"></script>
    <script src="bootstrap.js"></script>
    <style>
        .container .row td{
            padding: 10px;
        }
        #box{
          padding-top:50px;
        }
       .add{
           margin:20px 0;
       }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-7 col-lg-offset-3" id="box" >
            <div>
                <button type="button" class="btn btn-success add" data-toggle="modal" data-target="#myModal">
                添加员工信息
                </button>
            </div>

            <table class="table table-striped">
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>部门</th>
                    <th>薪水</th>
                    <th>操作</th>
                </tr>

                <tr>
                    <td>张三</td>
                    <td>23</td>
                    <td>销售部</td>
                    <td>3000</td>
                    <td>
                        <button class="btn btn-danger btn-sm del">删除</button>
                        <button class="btn btn-info btn-sm edit">编辑</button>
                        <button class="btn btn-primary btn-sm">查看</button>
                    </td>
                </tr>

                 <tr class="handle">
                    <td>李四</td>
                    <td>32</td>
                    <td>保安部</td>
                    <td>5000</td>
                    <td>
                        <button class="btn btn-danger btn-sm del">删除</button>
                        <button class="btn btn-info btn-sm edit">编辑</button>
                        <button class="btn btn-primary btn-sm">查看</button>
                    </td>
                </tr>
            </table>
        </div>

    </div>

</div>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>

      <div class="modal-body">
          <div class="row">
              <div class="col-md-5 col-lg-offset-3">
                <form class="add_form edit_form">
                      <div class="form-group">
                        <label for="username">姓名</label>
                        <input type="text" class="form-control" id="username" placeholder="username">
                      </div>
                      <div class="form-group">
                        <label for="age">年龄</label>
                        <input type="text" class="form-control" id="age" placeholder="age">
                      </div>
                      <div class="form-group">
                        <label for="dep">部门</label>
                        <input type="text" id="dep" placeholder="dep" class="form-control">

                      </div>

                       <div class="form-group">
                        <label for="salary">薪水</label>
                        <input type="text" class="form-control" id="salary" placeholder="salary">
                      </div>
                  </form>
              </div>
          </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary add_save">Save changes</button>
        <button type="button" class="btn btn-primary edit_save" style="display: none">Save changes</button>
      </div>
    </div>
  </div>
</div>


<script>
         // 提炼出一个创建tr的函数
         function createTr(){
             var $tr=$("<tr>");
             $(".add_form :text").each(function(){
                 $tr.append($("<td>").html($(this).val()))
             });
             $handle=$(".handle td:last").clone();
             $tr.append($handle);
             return $tr
         }

         // 添加按钮
         $(".add_save").click(function(){
             $("#myModal").modal("hide");
             var $tr=createTr();
             $(".table tbody").append($tr)
         });

         // 删除按钮
         $("table").on("click",".del",function(){
            $(this).parent().parent().remove()
         });

         //编辑按钮
         $("table").on("click",".edit",function(){
             var $edit_obj=$(this).parent().parent();
             var arr=[];
             $(this).parent().siblings().each(function(){
                 arr.push($(this).text())
             });

             $(".edit_form :text").each(function(i){
                  $(this).val(arr[i])
             });

             $("#myModal").modal("show");

              $(".edit_save").show().prev().hide();
              $(".edit_save").click(function(){
                  $("#myModal").modal("hide");
                  // 创建tr标签
                 var $tr=createTr();
                 $edit_obj.replaceWith($tr);
                 $(".edit_save").hide().prev().show();
             });

          })

</script>
</body>
</html>
相关文章
|
3天前
|
云安全 数据采集 人工智能
古茗联名引爆全网,阿里云三层防护助力对抗黑产
阿里云三层校验+风险识别,为古茗每一杯奶茶保驾护航!
古茗联名引爆全网,阿里云三层防护助力对抗黑产
|
3天前
|
存储 机器学习/深度学习 人工智能
大模型微调技术:LoRA原理与实践
本文深入解析大语言模型微调中的关键技术——低秩自适应(LoRA)。通过分析全参数微调的计算瓶颈,详细阐述LoRA的数学原理、实现机制和优势特点。文章包含完整的PyTorch实现代码、性能对比实验以及实际应用场景,为开发者提供高效微调大模型的实践指南。
495 1
kde
|
3天前
|
人工智能 关系型数据库 PostgreSQL
n8n Docker 部署手册
n8n是一款开源工作流自动化平台,支持低代码与可编程模式,集成400+服务节点,原生支持AI与API连接,可自托管部署,助力团队构建安全高效的自动化流程。
kde
332 3
|
3天前
|
存储 人工智能 Java
AI 超级智能体全栈项目阶段四:学术分析 AI 项目 RAG 落地指南:基于 Spring AI 的本地与阿里云知识库实践
本文介绍RAG(检索增强生成)技术,结合Spring AI与本地及云知识库实现学术分析AI应用,利用阿里云Qwen-Plus模型提升回答准确性与可信度。
226 91
AI 超级智能体全栈项目阶段四:学术分析 AI 项目 RAG 落地指南:基于 Spring AI 的本地与阿里云知识库实践
|
4天前
|
传感器 人工智能 算法
数字孪生智慧水务系统,三维立体平台,沃思智能
智慧水务系统融合物联网、数字孪生与AI技术,实现供水全流程智能监测、预测性维护与动态优化。通过实时数据采集与三维建模,提升漏损控制、节能降耗与应急响应能力,推动水务管理从经验驱动迈向数据驱动,助力城市水资源精细化、可持续化管理。
282 143
|
18天前
|
存储 关系型数据库 分布式数据库
PostgreSQL 18 发布,快来 PolarDB 尝鲜!
PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
|
7天前
|
人工智能 移动开发 自然语言处理
阿里云百炼产品月刊【2025年9月】
本月通义千问模型大升级,新增多模态、语音、视频生成等高性能模型,支持图文理解、端到端视频生成。官网改版上线全新体验中心,推出高代码应用与智能体多模态知识融合,RAG能力增强,助力企业高效部署AI应用。
353 1