jQuery开发补充笔记

时间:2022-07-28
本文章向大家介绍jQuery开发补充笔记,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

[TOC]

0x00 前言简介

什么JQuery? jQuery是一个快速、简洁的JavaScript框架,是继Prototype之后又一个优秀的JavaScript代码库(或JavaScript框架)。jQuery设计的宗旨是“write Less,Do More”,即倡导写更少的代码,做更多的事情。它封装JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互。

jQuery的核心特性可以总结为:具有独特的链式语法和短小清晰的多功能接口;具有高效灵活的css选择器,并且可对CSS选择器进行扩展;拥有便捷的插件扩展机制和丰富的插件。jQuery兼容各种主流浏览器,如IE 6.0+、FF 1.5+、Safari 2.0+、Opera 9.0+等

JQuery的作用: ​1. 写更少的代码,做更多的事情: write Less ,Do more

  1. 将我们页面的JS代码和HTML页面代码进行分离
  2. 提高我们的工作效率,轻松的进行前端开发

JQuery中的选择器:

  • 基本选择器
    • ID选择器: #ID的名称
    • 类选择器: 以 . 开头 .类名
    • 元素选择器: 标签的名称
    • 通配符选择器: *
    • 选择器,选择器: 选择器1,选择器2
  • 层级选择器
    • 子元素选择器: 选择器1 > 选择器2
    • 后代选择器: 选择器1 儿孙
    • 相邻兄弟选择器: 选择器1 + 选择器2 : 找出紧挨着的一个弟弟
    • 找出所有弟弟: 选择器1~ 选择器2 : 找出所有的弟弟
  • 属性选择器:
    • 选择器[href][title] : 多个属性
    • 选择器[href][title=’test’] : 多个属性,包含值

基本过滤器:

  • ​ 选择器:first 找出的是第一个
  • ​ :last
  • ​ :even 找出索引为偶数
  • ​ :odd 找出奇数索引
  • ​ :gt(index) 大于索引
  • ​ :lt(index) 小于
  • ​ :eq(index) 等于

表单过滤器:

  • :input 找出所有输入项: input textarea select
  • ​:text
  • :password
  • option:selected

0x01 jQuery 使用说明

jQuery调用的三种形式:

jQuery(document).
$(document).
$(function(){});

基础示例:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <script>
    /**文档加载完成执行**/
    //方式1
    jQuery(document).ready(function(){
      alert("Read");
    })
    //方式2
    $(document).ready(function(){
      alert("Reader");
    })
    //方式3
    $(function(){
      alert("Reader Reader")
    })
  </script>
</body>
</html>

JQ和JS之间的转换

  • JQ对象,只能调用JQ的属性和方法
  • JS对象,只能调用JS的属性和方法

基础示例:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Jquery/Javascript互换</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script src="jquery-2.1.0.min.js"></script>
</head>
<body>
  <button id="clk1">JS=>JQ对象</button>
  <button id="clk2">JQ=>JS对象</button>
  <pre id="change">
      【JQ和JS之间的转换】
      - JQ对象,只能调用JQ的属性和方法
      - JS对象,只能调用JS的属性和方法
  </pre>
  <hr>
  <button id="clk3">Show</button>
  <button id="clk4">Hide</button>
  <br>
  <img src="https://img2018.cnblogs.com/blog/1010141/201907/1010141-20190716105923289-1888756797.png" width="100px" height="100px" alt="Test" style="display: block;"/>
  <script>
      //示例1:
      $("#clk1").click(function(){
        var demo1 = document.getElementById("change");
        $(demo1).html("<b style='color:red'>JS对象转换成为JQ对象!</b>");
      });
      
      //示例2:
      $("#clk2").click(function(){
       var $demo2 = $('#change');
       var demo2 = $demo2.get(0); //或者$demo2[0]
       demo2.innerHTML="<b style='color:green'>JQ对象转换成为JS对象!</b>";
      });

      //示例3
      $(function(){
        $('#clk3').click(function(){
          $("img").show(2000);
          $("img").animate({width:"200px",opacity:"0.9"})
          $("img").fadeIn(2000);
        })

        $('#clk4').click(function(){
          $("img").hide(3000);
          $("img").fadeOut(1000);
        })
      });
    </script>
</body>
</html>

WeiyiGeek.

jQuery定时广告弹出和隐藏

  • 定时器:
​setInterval  clearInterval
​setTimeout   clearTimeout
  • 显示:
img.style.display  = "block"
$("img").show()
  • 隐藏
img.style.display  = "none"
$("img").hide()
  • JQ完成表格的隔行换色 和 输入框选中; 修改行的颜色的CSS方法:
​	row.bgColor ="red"
​	row.style.backgroundColor = "black"
​	row.style.background = "red"
​	"background-color:red"
​	"background:red"

基础示例:

<H3>Test ConvetTO-Html</H3>
<table style='border:1px solid red' border="1px">
<tr><th><input type="checkbox" name="checkAll" id="Demo"></th><th>Name</th><th>Version</th><th>InstanceId</th><th>UI</th></tr>
<tr><th><input type="checkbox" name="checkAll"></th><td>Windows PowerShell ISE Host</td><td>5.1.18362.145</td><td>44e2ee19-5d0a-4b3f-b66e-8c8870cd627a</td><td>System.Management.Automation.Internal.Host.InternalHostUserInterface</td></tr>
<tr><th><input type="checkbox" name="checkAll"></th><td>Windows PowerShell ISE Host</td><td>5.1.18362.145</td><td>44e2ee19-5d0a-4b3f-b66e-8c8870cd627a</td><td>System.Management.Automation.Internal.Host.InternalHostUserInterface</td></tr>
<tr><th><input type="checkbox" name="checkAll"></th><td>Windows PowerShell ISE Host</td><td>5.1.18362.145</td><td>44e2ee19-5d0a-4b3f-b66e-8c8870cd627a</td><td>System.Management.Automation.Internal.Host.InternalHostUserInterface</td></tr>
<tr><th><input type="checkbox" name="checkAll"></th><td>Windows PowerShell ISE Host</td><td>5.1.18362.145</td><td>44e2ee19-5d0a-4b3f-b66e-8c8870cd627a</td><td>System.Management.Automation.Internal.Host.InternalHostUserInterface</td></tr>
</table>
</body></html>
<script>
  $(function(){
    $("#Demo").click(function(){
      $("input[type='checkbox']:gt(0)").prop("checked",this.checked);
    })

    //方式1
    //$("tr:first").css("background-color","green");
    //$("tr:odd").css("background-color","deeppink");

    var row = $("tr").length
    console.info("Tr 标签格数 :" + row)
    for(i=2; i <= row; i++){
      //默认是从以1开始
      if(i % 2 == 0){
        $("tr:nth-child("+i+")").css("background-color","deeppink");
      } else if( i % 2 != 0){
        $("tr:nth-child("+i+")").css("background-color","yellow");
      }
    }
  });
</script>

WeiyiGeek.

使用JQ完成省市联动效果

需求分析: 在我们的注册表单中,通常我们需要知道用户的籍贯,需要一个给用选择的项,当用户选中了省份之后,列出省下面所有的城市 技术分析:

  1. 准备工作 : 城市信息的数据
  2. 添加节点 : appendChild (JS)
    1. append : 添加子元素到末尾
    2. appendTo : 给自己找一个爹,将自己添加到别人家里
    3. prepend : 在子元素前面添加
    4. after : 在自己的后面添加一个兄弟
    5. empty : 清空节点
  3. 遍历的操作:123456789101112131415161718192021222324//J对象循环遍历var city = ['北京','上海','天津','重庆','深圳']//方式1(city).each(function(i,n){ console.info(i + " : " + n);})//方式2

基础示例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>城市联动</title>
  <script src="jquery-2.1.0.min.js"></script>
  <script>
    var provinces = [
				["深圳市","东莞市","惠州市","广州市"],
				["长沙市","岳阳市","株洲市","湘潭市"],
				["厦门市","福州市","漳州市","泉州市"]
			];

    $(function(){
				$("#province").change(function(){
					//得到城市信息
					var cities = provinces[this.value];

          if( this.value == -1){
            alert("请选择城市信息!");
          }
          //清空城市select中的option
          /*var $city = $("#city"); 	//将JQ对象转成JS对象进行清空
          var citySelect = $city.get(0)
          citySelect.options.length = 0;*/
          $("#city").empty();  //采用JQ的方式清空
      
					//遍历城市数据
					$(cities).each(function(i,n){
						$("#city").append("<option value="+n+">"+n+"</option>");
					});
				});
			});
  </script>
</head>
<body>
  <!--选择省份-->
  <select id="province">
      <option value="-1">--请选择--</option>
      <option value="0">广东省</option>
      <option value="1">湖南省</option>
      <option value="2">福建省</option>
    </select>
    <!--选择城市-->
    <select id="city"></select>
</body>
</html>

WeiyiGeek.

JQ完成下拉列表左右选择

<script type="text/javascript" src="../js/jquery-1.11.0.js" ></script>
<script>
  $(function(){
    $("#a1").click(function(){
      //找到被选中的那一项
      //将被选中项添加到右边
      $("#rightSelect").append($("#leftSelect option:selected"));
    });
    
    //将左边所有商品移动到右边
    $("#a2").click(function(){
      $("#rightSelect").append($("#leftSelect option"));
    });
  });
</script>


<!--左边-->
<div style="float: left;">
  已有商品<br />
  <select multiple="multiple" id="leftSelect">
    <option>华为</option>
    <option>小米</option>
    <option>锤子</option>
    <option>oppo</option>
  </select>
  <br />
  <a href="#" id="a1" > &gt;&gt; </a> <br/>
  <a href="#" id="a2"> &gt;&gt;&gt; </a>
</div>

<!--右边-->
<div style="float: right;"> 
  未有商品<br />
  <select multiple="multiple" id="rightSelect">
    <option>苹果6</option>
    <option>肾7</option>
    <option>诺基亚</option>
    <option>波导</option>
  </select>
  <br />
  <a href="#"> &lt;&lt; </a> <br />
  <a href="#"> &lt;&lt;&lt; </a>
</div>

WeiyiGeek.

jQuery表单效验 需求:

  • 用户名和密码长度验证
  • 用户名和密码的输入的特殊字符验证
  • 采用md5加密传输用户输入的密码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>表单效验</title>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
    <script src="http://www.gongjuji.net/content/files/jquery.md5.js"></script>
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="http://cdn.bootcss.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <style>
        .req {
            color:red;
        }
        .onErrorTips {
            color:red;
            font: 1em sans-serif;
        }
    </style>
</head>
<body>
    <form action="index.html" method="GET">
        <div class="loginInput">
            <input type="text" name="username" id="username" class="depend">
        </div>
        <div class="loginInput">
            <input type="password" name="passowrd" id="password" class="depend" placeholder="请输入8~16位的密码">
        </div>
        <input type="submit" value="登录">
        <input type="button" value="清空">
        <div class="loginRemember">
            <select name="loginRemember" id="">
                <option value="0">不记住登录</option>
                <option value="1">记住登录</option>
            </select>    
        </div>
    </form>
    <script>
    $(function(){
        var userReg = /^[0-9a-zA-Z_]+$/;
        var passReg = /^[0-9a-zA-Z!@#$%&*.,?]+$/;

        //必须项加上红星
        $(".loginInput").append("<font class='req'> * <font>");

        //效验绑定表单
        $(".depend").blur(function(){
            //获取输入框里面的值
            var val = $(this).val(); 
            
            //清除当前对象的提示信息
            $(this).parent().find("span").remove();  //体现链式编程

            //判读获取当前事件处理的对象
            if($(this).is("#username")){
                //用户名效验
                if(val.length <= 0 ||  val.length >= 16 ){
                    $(this).parent().append("<span class='onErrorTips'>用户名长度有误!</span>");
                }else if(!userReg.test(val)){
                    $(this).parent().append("<span class='onErrorTips'>用户名输入有误!</span>");
                }
            }
            
            if($(this).is("#password")){
                //密码效验
                if(val.length <= 7 ||  val.length > 18 ){
                    $(this).parent().append("<span class='onErrorTips'>密码长度有误!</span>");
                }else if(!passReg.test(val)){
                    $(this).parent().append("<span class='onErrorTips'>密码输入了特殊有误!</span>");
                }
            }

        }).focus(function(){
            $(this).triggerHandler("blur");
        }).keyup(function(){
            $(this).triggerHandler("blur");
        });

        $("input[value='清空']").click(function(){
            $(".depend").val("");
        });

        //点击表单里面的提交事件进行触发
        $("form").submit(function(){
            $(".depend").trigger("focus");
            //根据返回的true或者false决定是否进行表单提交,这里采用查找页面上是否存在错误信息来验证表单(值得学习)
            if($(".onErrorTips").length > 0){
                return false;
            }else{
                //md5加密输入
                $("#password").val($.md5($("#password").val()))
                return true;
            }
        });
    });
    </script>
</body>
</html>