Jquery使用

常用js插件

https://v3.bootcss.com/
https://www.bootcdn.cn/
http://www.fontawesome.com.cn/

一、jquery是什么?

1)Jquery简介

jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE,写更少的代码,做更多的事情。
它是轻量级的js库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器 (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)。
jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTML documents、events、实现动画效果,并且方便地为网站提供AJAX交互。
jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。
jQuery能够使用户的html页保持代码和html内容分离,也就是说,不用再在html里面插入一堆js来调用命令了,只需定义id即可。

2)什么是Jquery对象

jQuery 对象就是通过jQuery包装DOM对象后产生的对象。
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()    

二、查询标签选择器和筛选器

1)选择器

基本选择器            $("*")  $("#id")   $(".class")  $("element")  $(".class,p,div")
层级选择器            $(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div")
基本筛选器            $("li:first")  $("li:eq(2)")  $("li:even") $("li:gt(1)")
属性选择器            $('[id="div1"]')   $('["alex="sb"][id]')
表单选择器            $("[type='text']")----->$(":text")                    
只适用于input标签     $("input:checked")
View Code

选择器基本练习

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.2.1.min.js"></script>
</head>
<body>
    <div>hello div</div>
    <div class="div">hello div</div>
    <p>hello p</p>
    <p id="p1">hello</p>

    <div  class="outer">
        <div>
            <p>hellov p1</p>
        </div>
        <p>hellov p2</p>
    </div>
    <p>hellov p4</p>

    <div class="div">hello div
        <ul>
            <li>1111</li>
            <li>2222</li>
            <li>3333</li>
            <li>4444</li>
            <li>5555</li>
            <li>6666</li>
        </ul>
    </div>

    <p user="dsp">hellov sp</p>
    <p user="lsp">hellov sppp</p>

    <input type="text">
    <input type="button">
<script>
//    $("*").css("color","red")
//    $("div").css("color","red")
//    $("#p1").css("color","red")
//    $(".div").css("color","red")
//    $(".div,#p1").css("color","red")

//     $(".outer p").css("color","red")
//    $(".outer>p").css("color","red")
//    $(".outer+p").css("color","red")

//    $(".div li:first").css("color","green")
//    $(".div li:last").css("color","green")
//    $(".div li:eq(3)").css("color","green")     // 指的是第4个标签
//    $(".div li:lt(3)").css("color","green")     // 指的是前3个标签 1,2,3
//    $(".div li:gt(3)").css("color","green")    // 指的是从4开始的标签 4,5,*,*

//    $("[user]").css("color","green")
//    $("[user='lsp']").css("color","green")
//
//    $("[type='button']").css("width","300px")
    $(":button").css("width","300px")
</script>
</body>
</html>
View Code

2)筛选器

过滤筛选器
    $("li").eq(2)  $("li").first()  $("ul li").hasclass("test")
    
查找筛选器
    $("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()
View Code

3)小结:

$("#id")            // id选择器
$("tagName")        // 签选择器
$(".className")        // class选择器:
$("div.c1")          // 配和使用// 找到有c1 class类的div标签
$("*")                // 所有元素选择器
$("#id, .className, tagName")    组合选择器

层级选择器:x和y可以为任意选择器
$("x y");   // x的所有后代y(子子孙孙)
$("x > y"); // x的所有儿子y(儿子)
$("x + y")  // 找到所有紧挨在x后面的y
$("x ~ y")  // x之后所有的兄弟y

基本筛选器
first      // 第一个
last       // 最后一个
eq(index)  // 索引等于index的那个元素
even       // 匹配所有索引值为偶数的元素,从 0 开始计数
odd        // 匹配所有索引值为奇数的元素,从 0 开始计数
gt(index)  // 匹配所有大于给定索引值的元素
lt(index)  // 匹配所有小于给定索引值的元素
not(元素选择器)// 移除所有满足not条件的标签
has(元素选择器)// 选取所有包含一个或多个标签在其内的标签(指的是从后代元素找)

属性选择器:
[attribute]
[attribute=value]  // 属性等于
[attribute!=value] // 属性不等于
first() // 获取匹配的第一个元素
last() // 获取匹配的最后一个元素
not() // 从匹配元素的集合中删除与指定表达式匹配的元素
has() // 保留包含特定后代的元素,去掉那些不含有指定后代的元素。
eq() // 索引值等于指定值的元素
 
$("div:has(h1)")// 找到所有后代中有h1标签的div标签
$("div:has(.c1)")// 找到所有后代中有c1样式类的div标签
$("li:not(.c1)")// 找到所有不包含c1样式类的li标签
$("li:not(:has(a))")// 找到所有后代中不含a标签的li标签
示例
<input type="text">
<input type="password">
<input type="checkbox">
$("input[type='checkbox']");// 取到checkbox类型的input标签
$("input[type!='text']");// 取到类型不是text的input标签
属性选择器示例

自定义模态框,使用jQuery实现弹出和隐藏功能。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>自定义模态框</title>
  <style>
    .cover {
      position: fixed;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      background-color: darkgrey;
      z-index: 999;
    }
    .modal {
      width: 600px;
      height: 400px;
      background-color: white;
      position: fixed;
      left: 50%;
      top: 50%;
      margin-left: -300px;
      margin-top: -200px;
      z-index: 1000;
    }
    .hide {
      display: none;
    }
  </style>
</head>
<body>
<input type="button" value="弹" id="i0">

<div class="cover hide"></div>
<div class="modal hide">
  <label for="i1">姓名</label>
  <input id="i1" type="text">
   <label for="i2">爱好</label>
  <input id="i2" type="text">
  <input type="button" id="i3" value="关闭">
</div>
<!--<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>-->
<script src="jquery-3.3.1.min.js"></script>
<script>
  var tButton = $("#i0")[0];
  tButton.onclick=function () {
    var coverEle = $(".cover")[0];
    var modalEle = $(".modal")[0];

    $(coverEle).removeClass("hide");
    $(modalEle).removeClass("hide");
  };

  var cButton = $("#i3")[0];
  cButton.onclick=function () {
    var coverEle = $(".cover")[0];
    var modalEle = $(".modal")[0];

    $(coverEle).addClass("hide");
    $(modalEle).addClass("hide");
  }
</script>
</body>
</html>
静态对话框示例

4)针对表单的常用筛选

:text
:password
:file
:radio
:checkbox

:submit
:reset
:button
表单常用筛选
$(":checkbox")  // 找到所有的checkbox
示例

4.1)表单的对象属性

$(":checkbox")  // 找到所有的checkbox
表单对象属性

示例一:找到可用的input标签

<form>
  <input name="email" disabled="disabled" />
  <input name="id" />
</form>

$("input:enabled")  // 找到可用的input标签
示例:找input标签

示例二: 找到被选中的option

<select id="s1">
  <option value="beijing">北京市</option>
  <option value="shanghai">上海市</option>
  <option selected value="guangzhou">广州市</option>
  <option value="shenzhen">深圳市</option>
</select>

$(":selected")  // 找到所有被选中的option
示例:找到选中的option

5)上下,父亲,儿子,兄弟元素选择

下一个元素:
    $("#id").next()
    $("#id").nextAll()
    $("#id").nextUntil("#i2")
上一个元素:
    $("#id").prev()
    $("#id").prevAll()
    $("#id").prevUntil("#i2")
父亲元素:
    $("#id").parent()
    $("#id").parents()  // 查找当前元素的所有的父辈元素
    $("#id").parentsUntil() // 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止。
儿子和兄弟元素:
    $("#id").children();// 儿子们
    $("#id").siblings();// 兄弟们
元素选择概况

6)查找和筛选

查找
    搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。
    $("div").find("p")等价于$("div p")
筛选
    筛选出与指定表达式匹配的元素集合。这个方法用于缩小匹配的范围。用逗号分隔多个表达式。
    $("div").filter(".c1")等价于 $("div.c1" // 从结果集中过滤出有c1样式类的

三、操作标签(样式操作,文本操作,属性操作,文档操作)

1)样式操作

查找
    搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。
    $("div").find("p")等价于$("div p")
筛选
    筛选出与指定表达式匹配的元素集合。这个方法用于缩小匹配的范围。用逗号分隔多个表达式。
    $("div").filter(".c1")等价于 $("div.c1" // 从结果集中过滤出有c1样式类的
    
----------------------------------------------------------------------------------------------------------------------
动作类
    addClass();        // 添加指定的CSS类名。
    removeClass();    // 移除指定的CSS类名。
    toggleClass();    // 切换CSS类名,如果有就移除,如果没有就添加
判断类
    hasClass();        // 判断样式存不存在
位置类
    offset()        // 获取匹配元素在当前窗口的相对偏移或设置元素位置
    position()        // 获取匹配元素相对父元素的偏移
    scrollTop()        // 获取匹配元素相对滚动条顶部的偏移
    scrollLeft()    // 获取匹配元素相对滚动条左侧的偏移
    注意: .offset()方法允许我们检索一个元素相对于文档(document)的当前位置。
         与.position()的差别在于: .position()是相对于相对于父级元素的位移。

尺寸
    height()
    width()
    innerHeight()
    innerWidth()
    outerHeight()
    outerWidth()
样式操作方法
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>位置相关示例之返回顶部</title>
  <style>
    .c1 {
      width: 100px;
      height: 200px;
      background-color: red;
    }

    .c2 {
      height: 50px;
      width: 50px;

      position: fixed;
      bottom: 15px;
      right: 15px;
      background-color: #2b669a;
    }
    .hide {
      display: none;
    }
    .c3 {
      height: 100px;
    }
  </style>
</head>
<body>
<button id="b1" class="btn btn-default">点我</button>
<div class="c1"></div>
<div class="c3">1</div>
<div class="c3">2</div>
<div class="c3">3</div>
<div class="c3">4</div>
<div class="c3">5</div>
<div class="c3">6</div>
<div class="c3">7</div>
<div class="c3">8</div>
<div class="c3">9</div>
<div class="c3">10</div>
<div class="c3">11</div>
<div class="c3">12</div>
<div class="c3">13</div>
<div class="c3">14</div>
<div class="c3">15</div>
<div class="c3">16</div>
<div class="c3">17</div>
<div class="c3">18</div>
<div class="c3">19</div>
<div class="c3">20</div>
<div class="c3">21</div>
<div class="c3">22</div>
<div class="c3">23</div>
<div class="c3">24</div>
<div class="c3">25</div>
<div class="c3">26</div>
<div class="c3">27</div>
<div class="c3">28</div>
<div class="c3">29</div>
<div class="c3">30</div>
<div class="c3">31</div>
<div class="c3">32</div>
<div class="c3">33</div>
<div class="c3">34</div>
<div class="c3">35</div>
<div class="c3">36</div>
<div class="c3">37</div>
<div class="c3">38</div>
<div class="c3">39</div>
<div class="c3">40</div>
<div class="c3">41</div>
<div class="c3">42</div>
<div class="c3">43</div>
<div class="c3">44</div>
<div class="c3">45</div>
<div class="c3">46</div>
<div class="c3">47</div>
<div class="c3">48</div>
<div class="c3">49</div>
<div class="c3">50</div>
<div class="c3">51</div>
<div class="c3">52</div>
<div class="c3">53</div>
<div class="c3">54</div>
<div class="c3">55</div>
<div class="c3">56</div>
<div class="c3">57</div>
<div class="c3">58</div>
<div class="c3">59</div>
<div class="c3">60</div>
<div class="c3">61</div>
<div class="c3">62</div>
<div class="c3">63</div>
<div class="c3">64</div>
<div class="c3">65</div>
<div class="c3">66</div>
<div class="c3">67</div>
<div class="c3">68</div>
<div class="c3">69</div>
<div class="c3">70</div>
<div class="c3">71</div>
<div class="c3">72</div>
<div class="c3">73</div>
<div class="c3">74</div>
<div class="c3">75</div>
<div class="c3">76</div>
<div class="c3">77</div>
<div class="c3">78</div>
<div class="c3">79</div>
<div class="c3">80</div>
<div class="c3">81</div>
<div class="c3">82</div>
<div class="c3">83</div>
<div class="c3">84</div>
<div class="c3">85</div>
<div class="c3">86</div>
<div class="c3">87</div>
<div class="c3">88</div>
<div class="c3">89</div>
<div class="c3">90</div>
<div class="c3">91</div>
<div class="c3">92</div>
<div class="c3">93</div>
<div class="c3">94</div>
<div class="c3">95</div>
<div class="c3">96</div>
<div class="c3">97</div>
<div class="c3">98</div>
<div class="c3">99</div>
<div class="c3">100</div>

<button id="b2" class="btn btn-default c2 hide">返回顶部</button>
<script src="jquery-3.2.1.min.js"></script>
<script>
  $("#b1").on("click", function () {
    $(".c1").offset({left: 200, top:200});
  });


  $(window).scroll(function () {
    if ($(window).scrollTop() > 100) {
      $("#b2").removeClass("hide");
    }else {
      $("#b2").addClass("hide");
    }
  });
  $("#b2").on("click", function () {
    $(window).scrollTop(0);
  })
</script>
</body>
</html>
返回顶部示例

2)文本操作

HTML代码:
    html()// 取得第一个匹配元素的html内容
    html(val)// 设置所有匹配元素的html内容
文本值:
    text()// 取得所有匹配元素的内容
    text(val)// 设置所有匹配元素的内容
值:
    val()// 取得第一个匹配元素的当前值
    val(val)// 设置所有匹配元素的值
    val([val1, val2])// 设置checkbox、select的值
文本操作方法

获取被选中的checkbox或radio的值:

<label for="c1"></label>
<input name="gender" id="c1" type="radio" value="0">
<label for="c2"></label>
<input name="gender" id="c2" type="radio" value="1">

$("input[name='gender']:checked").val()
示例

2.1)定义登录验证

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>文本操作之登录验证</title>
  <style>
    .error {
      color: red;
    }
  </style>
</head>
<body>

<form action="">
  <div>
    <label for="input-name">用户名</label>
    <input type="text" id="input-name" name="name">
    <span class="error"></span>
  </div>
  <div>
    <label for="input-password">密码</label>
    <input type="password" id="input-password" name="password">
    <span class="error"></span>
  </div>
  <div>
    <input type="button" id="btn" value="提交">
  </div>
</form>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
  $("#btn").click(function () {
    var username = $("#input-name").val();
    var password = $("#input-password").val();

    if (username.length === 0) {
      $("#input-name").siblings(".error").text("用户名不能为空");
    }
    if (password.length === 0) {
      $("#input-password").siblings(".error").text("密码不能为空");
    }
  })
</script>
</body>
</html>
登录验证

 3)属性操作

用于ID等或自定义属性:
    attr(attrName)// 返回第一个匹配元素的属性值
    attr(attrName, attrValue)// 为所有匹配元素设置一个属性值
    attr({k1: v1, k2:v2})// 为所有匹配元素设置多个属性值
    removeAttr()// 从每一个匹配的元素中删除一个属性
用于checkbox和radio
    prop() // 获取属性
    removeProp() // 移除属性
属性方法
<input type="checkbox" value="1">
<input type="radio" value="2">
<script>
  $(":checkbox[value='1']").prop("checked", true);
  $(":radio[value='2']").prop("checked", true);
</script>
属性示例

4)文档操作

添加到指定元素内部的后面
    $(A).append(B)// 把B追加到A
    $(A).appendTo(B)// 把A追加到B
添加到指定元素内部的前面
    $(A).prepend(B)// 把B前置到A
    $(A).prependTo(B)// 把A前置到B
添加到指定元素外部的后面
    $(A).after(B)// 把B放到A的后面
    $(A).insertAfter(B)// 把A放到B的后面
添加到指定元素外部的前面
    $(A).before(B)// 把B放到A的前面
    $(A).insertBefore(B)// 把A放到B的前面
移除和清空元素
    remove()// 从DOM中删除所有匹配的元素。
    empty()// 删除匹配的元素集合中所有的子节点。

替换
    replaceWith()
    replaceAll()
克隆
    clone()// 参数
文档处理方法
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>克隆</title>
    <style>
        #b1 {
            background-color: deeppink;
            padding: 5px;
            color: white;
            margin: 5px;
        }

        #b2 {
            background-color: dodgerblue;
            padding: 5px;
            color: white;
            margin: 5px;
        }
    </style>
</head>
<body>

<button id="b1">屠龙宝刀,点击就送</button>
<hr>
<button id="b2">屠龙宝刀,点击就送</button>

<script src="jquery-3.3.1.min.js"></script>
<script>
    // clone方法不加参数true,克隆标签但不克隆标签带的事件
    $("#b1").on("click", function () {
        $(this).clone().insertAfter(this);
    });
    // clone方法加参数true,克隆标签并且克隆标签带的事件
    $("#b2").on("click", function () {
        $(this).clone(true).insertAfter(this);
    });
</script>
</body>
</html>
点击触发复制功能示例

五、事件处理

1)常用事件

click(function(){...})
hover(function(){...})
blur(function(){...})
focus(function(){...})
change(function(){...})
keyup(function(){...})

  1.1)click事件示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>键盘事件示例</title>
</head>
<body>

<table border="1">
    <thead>
    <tr>
        <th>#</th>
        <th>姓名</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td><input type="checkbox"></td>
        <td>Egon</td>
        <td>
            <select>
                <option value="1">上线</option>
                <option value="2">下线</option>
                <option value="3">停职</option>
            </select>
        </td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>Alex</td>
        <td>
            <select>
                <option value="1">上线</option>
                <option value="2">下线</option>
                <option value="3">停职</option>
            </select>
        </td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>Yuan</td>
        <td>
            <select>
                <option value="1">上线</option>
                <option value="2">下线</option>
                <option value="3">停职</option>
            </select>
        </td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>EvaJ</td>
        <td>
            <select>
                <option value="1">上线</option>
                <option value="2">下线</option>
                <option value="3">停职</option>
            </select>
        </td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>Gold</td>
        <td>
            <select>
                <option value="1">上线</option>
                <option value="2">下线</option>
                <option value="3">停职</option>
            </select>
        </td>
    </tr>
    </tbody>
</table>

<input type="button" id="b1" value="全选">
<input type="button" id="b2" value="取消">
<input type="button" id="b3" value="反选">

<script src="jquery-3.3.1.min.js"></script>
<script>
    // 全选
    $("#b1").on("click", function () {
        $(":checkbox").prop("checked", true);
    });
    // 取消
    $("#b2").on("click", function () {
        $(":checkbox").prop("checked", false);
    });
    // 反选
    $("#b3").on("click", function () {
        $(":checkbox").each(function () {
            var flag = $(this).prop("checked");
            $(this).prop("checked", !flag);
        })
    });
//    // 按住shift键,批量操作
//    // 定义全局变量
//    var flag = false;
//    // 全局事件,监听键盘shift按键是否被按下
//    $(window).on("keydown", function (e) {
////    alert(e.keyCode);
//        if (e.keyCode === 16) {
//            flag = true;
//        }
//    });
//    // 全局事件,shift按键抬起时将全局变量置为false
//    $(window).on("keyup", function (e) {
//        if (e.keyCode === 16) {
//            flag = false;
//        }
//    });
//    // select绑定change事件
//    $("table select").on("change", function () {
//        // 是否为批量操作模式
//        if (flag) {
//            var selectValue = $(this).val();
//            // 找到所有被选中的那一行的select,选中指定值
//            $("input:checked").parent().parent().find("select").val(selectValue);
//        }
//    })
</script>
</body>
</html>
全选反选示例

1.2)hover示例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>hover示例</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .nav {
      height: 40px;
      width: 100%;
      background-color: #3d3d3d;
      position: fixed;
      top: 0;
    }

    .nav ul {
      list-style-type: none;
      line-height: 40px;
    }

    .nav li {
      float: left;
      padding: 0 10px;
      color: #999999;
      position: relative;
    }
    .nav li:hover {
      background-color: #0f0f0f;
      color: white;
    }

    .clearfix:after {
      content: "";
      display: block;
      clear: both;
    }

    .son {
      position: absolute;
      top: 40px;
      right: 0;
      height: 50px;
      width: 100px;
      background-color: #00a9ff;
      display: none;
    }

    .hover .son {
      display: block;
    }
  </style>
</head>
<body>
<div class="nav">
  <ul class="clearfix">
    <li>登录</li>
    <li>注册</li>
    <li>购物车
      <p class="son hide">
        空空如也...
      </p>
    </li>
  </ul>
</div>
<script src="jquery-3.3.1.min.js"></script>
<script>
$(".nav li").hover(
  function () {
    $(this).addClass("hover");
  },
  function () {
    $(this).removeClass("hover");
  }
);
</script>
</body>
</html>
hover示例

1.3)实时监听input输入值变化示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>实时监听input输入值变化</title>
</head>
<body>
<input type="text" id="i1">

<script src="jquery-3.3.1.min.js"></script>
<script>
    /*
     * oninput是HTML5的标准事件
     * 能够检测textarea,input:text,input:password和input:search这几个元素的内容变化,
     * 在内容修改后立即被触发,不像onchange事件需要失去焦点才触发
     * oninput事件在IE9以下版本不支持,需要使用IE特有的onpropertychange事件替代
     * 使用jQuery库的话直接使用on同时绑定这两个事件即可。
     * */
    $("#i1").on("input propertychange", function () {
        alert($(this).val());
    })
</script>
</body>
</html>
监听input输入值内容

2)事件方法(事件绑定,移除事件,阻止后续事件执行)

事件绑定
    .on( events [, selector ],function(){})
        events: 事件
        selector: 选择器(可选的)
        function: 事件处理函数
    
移除事件
    .off( events [, selector ][,function(){}])
    off() 方法移除用 .on()绑定的事件处理程序。
        events: 事件
        selector: 选择器(可选的)
        function: 事件处理函数    
    
阻止后续事件执行
    return false; // 常见阻止表单提交等
    
注意:
    像click、keydown等DOM中定义的事件,我们都可以使用`.on()`方法来绑定事件,
    但是`hover`这种jQuery中定义的事件就不能用`.on()`方法来绑定了。
事件方法

 如果使用事件委托的方式绑定hover事件处理函数,可以参照如下代码分两步绑定事件

('ul').on('mouseenter', 'li', function() {//绑定鼠标进入事件
    $(this).addClass('hover');
});
$('ul').on('mouseleave', 'li', function() {//绑定鼠标划出事件
    $(this).removeClass('hover');
});
示例

2.1)事件委托:是通过事件冒泡的原理,利用父标签去捕获子标签的事件。

表格中每一行的编辑和删除按钮都能触发相应的事件。
$("table").on("click", ".delete", function () {
  // 删除按钮绑定的事件
})
示例

六、Jqueryd的特殊方法

1)动画效果

// 基本
show([s,[e],[fn]])
hide([s,[e],[fn]])
toggle([s],[e],[fn])
// 滑动
slideDown([s],[e],[fn])
slideUp([s,[e],[fn]])
slideToggle([s],[e],[fn])
// 淡入淡出
fadeIn([s],[e],[fn])
fadeOut([s],[e],[fn])
fadeTo([[s],o,[e],[fn]])
fadeToggle([s,[e],[fn]])
// 自定义(了解即可)
animate(p,[s],[e],[fn])
动画效果方法
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>点赞动画示例</title>
  <style>
    div {
      position: relative;
      display: inline-block;
    }
    div>i {
      display: inline-block;
      color: red;
      position: absolute;
      right: -16px;
      top: -5px;
      opacity: 1;
    }
  </style>
</head>
<body>

<div id="d1">点赞</div>
<script src="jquery-3.3.1.min.js"></script>
<script>
  $("#d1").on("click", function () {
    var newI = document.createElement("i");
    newI.innerText = "+1";
    $(this).append(newI);
    $(this).children("i").animate({
      opacity: 0
    }, 1000)
  })
</script>
</body>
</html>
点赞特效示例

2)each迭代

2.1)each迭代数组

    一个通用的迭代函数,它可以用来无缝迭代对象和数组。数组和类似数组的对象通过一个长度属性
  (如一个函数的参数对象)来迭代数字索引,从0到length - 1。其他对象通过其属性名进行迭代。

li =[10,20,30,40]
$.each(li,function(i, v){
  console.log(i, v);//index是索引,ele是每次循环的具体元素。
})


输出:
010
120
230
340
each迭代数组

2.2)each(function(index, Element)):

描述:遍历一个jQuery对象,为每个匹配元素执行一个函数。
.each() 方法用来迭代jQuery对象中的每一个DOM元素。每次回调函数执行时,会传递当前循环次数作为参数(从0开始计数)。
由于回调函数是在当前DOM元素为上下文的语境中触发的,所以关键字 this 总是指向这个元素。
// 为每一个li标签添加foo
$("li").each(function(){
  $(this).addClass("c1");
});

注意: jQuery的方法返回一个jQuery对象,遍历jQuery集合中的元素 - 被称为隐式迭代的过程。
当这种情况发生时,它通常不需要显式地循环的 .each()方法:

也就是说,上面的例子没有必要使用each()方法,直接像下面这样写就可以了:
$("li").addClass("c1");  // 对所有标签做统一操作
each示例

  注意:在遍历过程中可以使用 return false提前结束each循环。

3).data(key, value)

   在匹配的元素集合中的所有元素上存储任意相关数据或返回匹配的元素集合中的第一个元素的给定名称的数据存储的值。

$("div").data("k",100);    //给所有div标签都保存一个名为k,值为100
$("div").data("k");        //返回第一个div标签中保存的"k"的值
$("div").removeData("k");  //移除元素上存放k对应的数据
data方法

七、实例练习

1)实现左侧菜单,点开菜单一,展示。其他收起来。单开菜单二展示,其他收起来....

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        function show(self) {
            $(self).next().removeClass("hide")
            $(self).parent().siblings().children(".con").addClass("hide")
        }
    </script>
    <style>
        .menu{
            height: 500px;
             30%;
            background-color: gainsboro;
            float: left;
        }
        .content{
            height: 500px;
             70%;
            background-color: darkgrey;
            float: left;
        }
        .title{
            line-height: 50px;
            background-color: darkseagreen;
            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>
View Code

2)实现下拉菜单

如京东案例

要求

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab</title>
    <script src="jquery-3.2.1.min.js"></script>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
             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>

<script>
    function tab(self) {
//        $(self).addClass("current");
//        $(self).siblings().removeClass("current")  // 2语句合并成下面一句
        $(self).addClass("current").siblings().removeClass("current")
//        alert($(self).attr("xxx"))  // c2 ,c3
        var s= $(self).attr("xxx");
        $("#"+s).removeClass("hide").siblings().addClass("hide");
    }
</script>
</body>
</html>
View Code

3)Jquery的属性prop用实现全选,取消,反选框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.2.1.min.js"></script>
</head>
<body>
    <button onclick="selectall();">全选</button>
    <button onclick="cancel();">取消</button>
    <button onclick="reverse();">反选</button>
    <table border="1" id="Table">
        <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>

<script>
//// 测试each的属性
//li=[10,20,30,40]
////dic={name:"yuan",sex:"male"}
//$.each(li,function(i,x){
//    console.log(i,x)
//})

function selectall() {
    $("table :checkbox").prop("checked",true)
}
function cancel() {
    $("table :checkbox").prop("checked",false)
}

function reverse() {
    $("table :checkbox").each(function(){
        if ($(this).prop("checked")){
            $(this).prop("checked",false)
        }else {
            $(this).prop("checked",true)
        }
    })
}
</script>
</body>
</html>
View Code

4)用clone实现加减框

 

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

<div id="outer">
    <div class="item">
         <input type="button" value="+" onclick="fun1(this)">
        <input type="text">
    </div>
</div>

<script src="jquery-3.2.1.min.js"></script>
<script>
     function fun1(self) {
         var Clone=$(self).parent().clone();
         Clone.children(":button").val("-").attr("onclick","func2(this)");
         $("#outer").append(Clone)
     }

     function func2(self) {
//         alert(123)
         $(self).parent().remove()
     }
</script>
</body>
</html>
View Code

5)实现静态对话框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .back{
            background-color: rebeccapurple;
            height: 2000px;
        }

        .shade{
            position: fixed;
            top: 0;
            bottom: 0;
            left:0;
            right: 0;
            background-color: coral;
            opacity: 0.4;
        }

        .hide{
            display: none;
        }

        .models{
            position: fixed;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -100px;
            height: 200px;
             200px;
            background-color: gold;

        }
    </style>
</head>
<body>
<div class="back">
    <input id="ID1" type="button" value="click" onclick="action1(this)">
</div>

<div class="shade hide"></div>
<div class="models hide">
    <input id="ID2" type="button" value="cancel" onclick="action2(this)">
</div>

<script src="jquery-3.2.1.min.js"></script>
<script>

      function action1(self) {
          $(self).parent().siblings().removeClass("hide");
      }

       function action2(self) {
          $(self).parent().parent().children(".shade,.models").addClass("hide")
      }
//    function action(act){
//        var ele=document.getElementsByClassName("shade")[0];
//        var ele2=document.getElementsByClassName("models")[0];
//        if(act=="show"){
//              ele.classList.remove("hide");
//              ele2.classList.remove("hide");
//        }else {
//              ele.classList.add("hide");
//              ele2.classList.add("hide");
//        }

//    }
</script>
</body>
</html>
View Code

 原文出处:https://www.cnblogs.com/liwenzhou/p/8178806.html

原文地址:https://www.cnblogs.com/linu/p/8447784.html