前端学习之jquery

一 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();

$("#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")[0].innerHTML
$("#msg").html();

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

 三 寻找元素(选择器和筛选器)

3.1   选择器

3.1.1 基本选择器 

$("*")  $("#id")   $(".class")  $("element")  $(".class,p,div") 

3.1.2 层级选择器  

$(".outer div")  $(".outer>div")   $(".outer+div")  $(".outer~div") 

3.1.3 基本筛选器 

$("li:first") $("li:last") $("li:eq(2)")  $("li:even")(索引偶数) $("li:odd")(索引奇数) 
$("li:gt(1)")(索引大于1)$("li:lt(1)")(索引小于1)
$("input:not(:checked)") 查找input标签中不是checked的标签

3.1.4 属性选择器  

$('[id="div1"]')   $('["alex="sb"][id]')   $('[attribute!=value]')  $('[attribute^=value]')以开头 
$('[attribute$=value]')以结尾  $('[attribute*=value]')包含
$('[alex') 查找所有有alex属性的标签

3.1.5 表单选择器  

$("[type='text']")----->$(":text")         注意只适用于input标签  : $("input:checked")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>

</head>
<body>

<p>p</p>
<p id="p2">pp</p>
<p class="p3">ppp</p>

<div>DIV</div>
<div class="outer">
    <p>PPP</p>
    <div class="inner">
        <p>PPPP</p>
    </div>
    <p>PPPPP</p>
</div>
<a href="">click</a>
<p>PPPPPPP</p>
<script src="jquery-3.2.1.js"></script>
<script>
        // $("*").css("color","red")
        // $("#p2").css("color","red")
        // $(".p3").css("color","red")
        // $(".p3,#p2").css("color","red")
        //  $(".outer p").css("color","red")
        //$(".outer>p").css("color","red")
        // $(".outer+p").css("color","red")
        // $(".outer~p").css("color","red")
</script>

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

        ul{
            list-style: none;
        }




    </style>
</head>
<body>


<ul>
    <li class="item">111</li>
    <li class="item">222</li>
    <li class="item">333</li>
    <li class="item">444</li>
    <li class="item">555</li>
</ul>

<div alex="sb">ALEX</div>
<div alex="sbb">ALEX</div>

<input type="text"  value="123">
<input type="password"  value="123">

<script src="jquery-3.2.1.js"></script>
<script>
//    -------------------------JS语法
//    var eles=document.getElementsByClassName("item");
//    for (var i=0;i<eles.length;i++){
//        eles[i].style.color="red";
//    }

//    筛选器----------------------------------

    // $("ul .item").css("color","green")
    //$("ul .item:first").css("color","green")
    //$("ul .item:last").css("color","green")
//    $("ul .item:eq(2)").css("color","green")
//    $("ul .item:even").css("color","green")
//    $("ul .item:odd").css("color","green")
//    $("ul .item:odd").css("color","green")
   // $("ul .item:gt(2)").css("color","green")
//    $("ul .item:lt(4)").css("color","green")

    // ------------------------属性选择器-----------------

    // $("[alex='sb']").css("color","green");

    // 表单选择器    : $(":text")

   // $("[type='text']").css("border","3px solid red")
   // $(":text").css("border","3px solid red")

</script>
</body>
</html>
例子

3.2 筛选器

3.2.1  过滤筛选器 

$("li").eq(2)  $("li").first()  $("ul li").hasclass("test") 返回布尔值
$("li")[1] $("li")[2]

 3.2.2 查找筛选器

 查找子标签   children子标签  find后代标签
$("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()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<ul>
    <li class="item active">111</li>
    <li class="item">222</li>
    <li class="item">333</li>
    <li class="item items">444</li>
    <li class="item">555</li>
</ul>
<div class="div1">
    <div class="div2">
        <p id="p1">PPP</p>
    </div>
    <p class="p2">PPPPP</p>
    <a href="">click</a>
</div>


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

<script>
    //  过滤筛选器

    // $("ul li:eq(2)").css("color","red");//eq(2)在字符串里面
    // $("ul li").eq(2).css("color","green");  // 推荐
//     var $ret=$("ul li").eq(3).hasClass("items");//返回布尔值
//    console.log($ret)


    //查找筛选器


    //  孩子组
//    console.log($(".div1").children("a"));//不写参数,操作所有的子标签
//    // $(".div1").children("p").css("color","red")  // 找子代(儿子层)
//    $(".div1").find("p").css("color","red");  // 找后代

   // 兄弟标签  next  nextAll   nextUntil

    // $(".active").next(".item").css("background-color","red")
    // $(".active").nextAll(".item").css("background-color","red")
   // $(".active").nextUntil(".items").css("background-color","red")   // ( )

   $(".items").siblings().css("color","red")


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

    <style>
          .menu{
              height: 500px;
               30%;
              background-color: gainsboro;
              float: left;
          }
          .content{
              height: 500px;
               70%;
              background-color: wheat;
              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>

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

    function show(self){
        // console.log(self.innerText);  // self是一个DOM对象

        // console.log($(self).text());    // $(self):当前操作标签对象

        $(self).next().removeClass("hide");//移除类名
        $(self).parent().siblings().children(".con").addClass("hide");

        //  $(self).next().removeClass("hide").parent().siblings().children(".con").addClass("hide")//合并写

    }
</script>
</body>
</html>
左侧菜单

四 操作元素(属性,css,文档处理)

4.1 属性操作     $操作可以同时操作多个标签,JS只能循环遍历,一次只能操作一个标签

--------------------------属性
$("").attr();      attr:操作自定义属性
$("").removeAttr();
$("").prop();   prop:操作固有属性 prop("属性名") -------取值 prop("属性名",属性值) -------赋值 $("").prop(“checked”,true);
$("").removeProp(); --------------------------Class类 $("").addClass(classname) $("").removeClass(classname) --------------------------HTML代码/文本/值 $("").html()无参时取文本标签,有参时将文本标签传入
$("").text()无参时取文本,有参时将文本标签当做文本传入 $("").val() 无参时取值,取input、button(按钮值)、select(取得是选项的id值),有参时相当于设值 --------------------------- $("").css("color","red")

 

注意:

<input id="chk1" type="checkbox" />是否可见
<input id="chk2" type="checkbox" checked="checked" />是否可见



<script>

//对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
//对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
//像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此
//需要使用prop方法去操作才能获得正确的结果。


//    $("#chk1").attr("checked")
//    undefined
//    $("#chk1").prop("checked")
//    false

//  ---------手动选中的时候attr()获得到没有意义的undefined-----------
//    $("#chk1").attr("checked")
//    undefined
//    $("#chk1").prop("checked")
//    true

    console.log($("#chk1").prop("checked"));//false
    console.log($("#chk2").prop("checked"));//true
    console.log($("#chk1").attr("checked"));//undefined
    console.log($("#chk2").attr("checked"));//checked
</script>

attr和prop
attr与prop
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>

        *
        {
            margin: 0;
            padding: 0;
        }
        .outer{
             80%;
            margin: 10px auto;

        }
          .nav li{
              list-style: none;
              float: left;
               33.1%;
              height: 40px;
              background-color: wheat;
              text-align: center;
              line-height: 40px;
              border-right: solid 2px green;
          }

        .content{
             100%;
            height: 400px;
            background-color: gray;
            float: left;
            clear: left;
        }

        ul  .active{
            background-color: #204982;
        }

        .hide{
            display: none;
        }

    </style>
</head>
<body>

<div class="outer">
    <ul class="nav">
       <li f="con1" class="active">菜单一</li>
       <li f="con2">菜单二</li>
       <li f="con3">菜单三</li>
    </ul>
    <div class="content">
        <div class="con1">1111</div>
        <div class="con2 hide">2222</div>
        <div class="con3 hide">3333</div>
    </div>

</div>

<script src="jquery-3.2.1.js"></script>
<script>
    var outer=document.getElementsByClassName("outer")[0];
    var lis=outer.getElementsByTagName("li");

    for (var i=0;i<lis.length;i++){
        lis[i].onclick=function(){
         //        console.log(this);       //  dom对象
         //        console.log($(this));  // jquery对象
         $(this).addClass("active").siblings().removeClass("active");

         var $name=$(this).attr("f");

          $("."+$name).removeClass("hide").siblings().addClass("hide");

        }
    }
</script>
</body>
</html>
Tab切换
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<ul>
    <li>111</li>
    <li class="item">222</li>
    <li>333</li>
</ul>
</body>

<script src="jquery-3.2.1.js"></script>
<script>
     //  jquery 的循环实现:两种方式  each


     // 方式一:
    arr=[123,456,"hello"];
    obj={"name":'egon',"age":22};

    //  $.each(arr,funtion(){})  格式

     $.each(arr,function(i,j){
         // console.log(i);  索引
         // console.log(j);  值
     });
      $.each(obj,function(i,j){
          console.log(i);   //对应key
          console.log(j);   //对应val
     });

    // 方式二:
     $("ul li").each(function(){
             //console.log($(this));//选项内容
         if ($(this).hasClass("item")){
             alert($(this).text())
         }
     })


</script>
</html>
jquery循环
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>


<h1>表格示例</h1>
    <button>全选</button>
    <button>反选</button>
    <button>取消</button>
<hr>
<table border="2px">
    <tr>
        <td><input type="checkbox"  class="item"></td>
        <td>111</td>
        <td>111</td>
        <td>111</td>
    </tr>
     <tr>
        <td><input type="checkbox" class="item"></td>
        <td>111</td>
        <td>111</td>
        <td>111</td>
    </tr>
     <tr>
        <td><input type="checkbox"  class="item"></td>
        <td>111</td>
        <td>111</td>
        <td>111</td>
    </tr>
     <tr>
       <td><input type="checkbox"  class="item"></td>
        <td>111</td>
        <td>111</td>
        <td>111</td>
    </tr>
</table>


<script src="jquery-3.2.1.js"></script>
<script>
    var eles=document.getElementsByTagName("button");
    // var inps=document.getElementsByClassName("item");
    for (var i=0;i<eles.length;i++){
         eles[i].onclick=function(){
             if (this.innerText=="全选"){
//                  for (var j=0;j<inps.length;j++){//js语法
//                      inps[j].checked=true
//                  }
                $(":checkbox").prop("checked",true);
             }
             else if(this.innerText=="取消"){
                 $(":checkbox").prop("checked",false);
             }
             else{
                 $(":checkbox").each(function(){

                     $(this).prop("checked",!$(this).prop("checked"));//简写
//                     if ($(this).prop("checked")){
//                         $(this).prop("checked",false)
//                     }
//                     else{
//                         $(this).prop("checked",true)
//                     }
                 })
             }

         }

    }

</script>
</body>
</html>
全选反选取消

4.2 文档处理

//创建一个标签对象
    $("<p>") $("<p></p>")
//内部插入 $("").append(content) ----->$("p").append("<b>Hello</b>"); $("").appendTo(content) ----->$("p").appendTo("div");前面的插入后面的标签最后
$(
"").prepend(content) ----->$("p").prepend("<b>Hello</b>");
$(
"").prependTo(content) —---->$("p").prependTo("#foo");前面的插入后面的标签最前
//外部插入 $("").after(content) ----->$("p").after("<b>Hello</b>"); $("").before(content) ----->$("p").before("<b>Hello</b>"); $("").insertAfter(content) ----->$("p").insertAfter("#foo");前面的插入后面的标签的后面
$(
"").insertBefore(content) ----->$("p").insertBefore("#foo");前面的插入后面的标签的前面
//替换 $("").replaceWith(content) ----->$("p").replaceWith("<b>Paragraph</b>"); //删除 $("").empty()清空容器,容器还在
$(
"").remove()相当于删除
//复制 $("").clone()

复制实例

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

</head>
<body>
            <div class="outer">
                <div class="item">
                        <input type="button" value="+" onclick="add(this);">
                        <input type="text">
                </div>
            </div>

<script src="jquery-1.11.3.min.js"></script>
    <script>
            //var $clone_obj=$(self).parent().clone();  // $clone_obj放在这个位置可以吗?
            function add(self){
                // 注意:if var $clone_obj=$(".outer .item").clone();会一遍二,二变四的增加
                 var $clone_obj=$(self).parent().clone();
                 $clone_obj.children(":button").val("-").attr("onclick","removed(this)");
                 $(self).parent().parent().append($clone_obj);
            }
           function removed(self){

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

           }

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

 4.3 each循环

// each的使用方式一:

$.each(obj,fn)

$.each([111,222,333],function(i,j){
     console.log(i)   // i : 索引
     console.log(j)   // j : 元素值
})    

$.each({"name":"alex"},function(i,j){
     console.log(i)   // i : key
     console.log(j)   // j : value
})            
                
// each的使用方式二:
   $(elector).each(fn)
   
   $(p).each(function(){
       $(this)
   })
  $(p).each(function(i,j){
       console.log(i)   // i : key
      console.log(j)   // j : value
   })

 4.4 css操作

   CSS
        $("").css(name|pro|[,val|fn])
    位置
        $("").offset([coordinates])标签窗口的body标签距离左边和上边的距离
$(
"").position()标签窗口距离有绝对定位标签距离左边和上边的距离,如果没有绝对定位的父标签,就是距离body标签左边和上边的距离
$(
"").scrollTop([val])返回顶部
$(
"").scrollLeft([val])返回左端
尺寸      内容区的尺寸
$(
"").height([val|fn])
     $(
"").width([val|fn])      内容区加padding的尺寸
$(
"").innerHeight() $("").innerWidth()      内容区、padding及border的尺寸
     $("").outerHeight(ture)内容区、padding、boddor及margin的尺寸
$(
"").outerHeight([soptions]) $("").outerWidth([options])

offset

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{
            margin: 0;
        }
    </style>
</head>
<body>
<h1>偏移量介绍</h1>
<p class="p1">first para</p>
<p class="p2">second para</p>

<button>offset</button>


<script src="jquery-3.2.1.js"></script>
<script>
     var $p_offset=$(".p1").offset();   // p1的偏移量对象

    var $left=$p_position.left; //距离左边的距离
    var $top=$p_position.top;   //距离顶部的距离


    $(".p2").text("the left: "+$left+"  the top: "+$top);


    $("button").click(function(){
         $(".p1").offset({left:100,top:200}); //设置窗口的视口

    })

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

position

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{
            margin: 0;
        }
        .t1{
              200px;
             height: 200px;
            background-color: wheat;
        }
        .box1{
             200px;
            height: 200px;
            background-color: darkgreen;
            position: relative;
        }
         .box2{
             100px;
            height: 100px;
            background-color: palevioletred;
        }
    </style>
</head>
<body>
<div class="t1"></div>
<div class="box1">
    <div class="box2">

    </div>
</div>
<p class="p2"></p>



<script src="jquery-3.2.1.js"></script>
<script>
     var $p_position=$(".box2").position();   // p1的position偏移量对象

    var $left=$p_position.left; //距离左边的距离
    var $top=$p_position.top;   //距离顶部的距离

    $(".p2").text("the left: "+$left+"  the top: "+$top);


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

scrollTop返回顶部(结合onscroll事件)

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

        *{
            margin: 0;
            padding: 0;
        }
        .back{
            background-color: wheat;
        }

        .top{
            background-color: darkblue;
            line-height: 40px;
             80px;
            color: white;
            position: fixed;
            right: 20px;
            bottom: 20px;
            text-align: center;
            display: none;

        }
    </style>
</head>
<body>
<div class="back">
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
</div>

<div class="top">返回顶部</div>
<script src="jquery-3.2.1.js"></script>
<script>
      $(".top").click(function(){
        $(window).scrollTop(0);
      });
      window.onscroll=function(){
          // console.log($(window).scrollTop())//距离窗口顶部的距离
          if($(window).scrollTop()>200){
              $(".top").show()
          }
          else{
              $(".top").hide()
          }
      };

</script>

</body>
</html>
View Code

元素长宽属性

五 事件绑定(事件没有on) 

   JS事件绑定一:
   
           <p onclick=f(this)></p>
            function f(obj){
                   obj:指向当前操作标签---- DOM对象    obj.innerText
                   $(obj):指向当前操作标签---- Jquery对象    $(obj).text()
            }
   
    JS事件绑定二:
   
           <p id="p1">PPP</p>
           var ele=document.getElementByid("p1");
           ele.onclick=function(){
              this-------:指向当前操作标签---- DOM对象
              $(this)
           }
   
    this在全局,代指window对象;
页面载入
    ready(fn)  //当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
    $(document).ready(function(){}) -----------> $(function(){})

事件处理on
$(
"").on(eve,[selector],[data],fn) // 在选择元素上绑定一个或多个事件的事件处理函数。 // .on的selector参数是筛选出调用.on方法的dom元素的指定子元素,如: // $('ul').on('click', 'li', function(){console.log('click');})就是筛选出ul下的li给其绑定 // click事件; [selector]参数的好处: 好处在于.on方法为动态添加的元素也能绑上指定事件;如: //$('ul li').on('click', function(){console.log('click');})的绑定方式和 //$('ul li').bind('click', function(){console.log('click');})一样;我通过js给ul添加了一个 //li:$('ul').append('<li>js new li<li>');这个新加的li是不会被绑上click事件的 //但是用$('ul').on('click', 'li', function(){console.log('click');}方式绑定,然后动态添加 //li:$('ul').append('<li>js new li<li>');这个新生成的li被绑上了click事件 [data]参数的调用: function myHandler(event) { alert(event.data.foo); } $("li").on("click", {foo: "bar"}, myHandler) myHandler就是date参数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="jquery-3.2.1.js"></script>
<script>
//    $("p").click(function(){
//        alert(123)
//    });

    // $("p").bind("click",function(){alert(456)})//舍弃的绑定事件的方法

    // window.onload=function(){}//js中的页面加载

   $(function(){    //简写方式$(document).ready(function(){ })
         $("p").css("color","red")
   });

   $(document).ready(function(){    //ready页面加载完再执行
       $("p").on("click",function(){
            alert(999)
        });

       $(".off_p").click(function(){
           $("p").off();                // 解除所有事件
        });

    });



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


//        $("li").click(function(){
//            alert(1234546)
//        })

//    $("ul").on("click","li",function(){//事件委派
//        alert(100)
//    })


</script>

</head>
<body>

<p>PPPP</p>


<ul>
    <li>111</li>
    <li>111</li>
    <li>111</li>
    <li>111</li>
</ul>

<button>add</button>
<button class="off_p">off</button>


</body>
</html>
View Code


 

六 动画效果

显示隐藏(从左向右显示、从右向左隐藏) show hide  toggle  

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

$(document).ready(function() {
    $("#hide").click(function () {
        $("p").hide(1000);//1000是时间
    });
    $("#show").click(function () {
        $("p").show(1000);
    });

//用于切换被选元素的 hide() 与 show() 方法。
    $("#toggle").click(function () {
        $("p").toggle();
    });
})

    </script>
    <link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>


    <p>hello</p>
    <button id="hide">隐藏</button>
    <button id="show">显示</button>
    <button id="toggle">切换</button>

</body>
</html>
显示隐藏

滑动(从上向下显示、从下向上隐藏) slideDown slideUp  slideToggle

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

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

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

</body>
</html>
滑动

淡入淡出(透明度改变)  fadeIn fadeOut fadeToggle fadeTo(透明度改变至某个程度)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-2.1.4.min.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;  80px;height: 80px;background-color: blueviolet"></div>

</body>
</html>
淡入淡出

回调函数  当某一个动作执行完成之后自动触发的函数

<!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>

七 扩展方法 (插件机制)

一 用JQuery写插件时,最核心的方两个方法

<script>
    
$.extend(object)      //为JQuery 添加一个静态方法。
$.fn.extend(object)   //为JQuery实例添加一个方法。


    jQuery.extend({
          min: function(a, b) { return a < b ? a : b; },
          max: function(a, b) { return a > b ? a : b; }
        });
    console.log($.min(3,4));

//-----------------------------------------------------------------------

$.fn.extend({
    "print":function(){
        for (var i=0;i<this.length;i++){
            console.log($(this)[i].innerHTML)
        }

    }
});

$("p").print();
</script>

二 定义作用域

      定义一个JQuery插件,首先要把这个插件的代码放在一个不受外界干扰的地方。如果用专业些的话来说就是要为这个插件定义私有作用域。外部的代码不能直接访问插件内部的代码。插件内部的代码不污染全局变量。在一定的作用上解耦了插件与运行环境的依赖。

function(a,b){return a+b})(3,5)

       (function ($) { })(jQuery);
//相当于
        var fn = function ($) { };
        fn(jQuery);

三 默认参数

定义了jQuery插件之后,如果希望某些参数具有默认值,那么可以以这种方式来指定。

/step01 定义JQuery的作用域
(function ($) {
    //step03-a 插件的默认值属性
    var defaults = {
        prevId: 'prevBtn',
        prevText: 'Previous',
        nextId: 'nextBtn',
        nextText: 'Next'
        //……
    };
    //step06-a 在插件里定义方法
    var showLink = function (obj) {
        $(obj).append(function () { return "(" + $(obj).attr("href") + ")" });
    }

    //step02 插件的扩展方法名称
    $.fn.easySlider = function (options) {
        //step03-b 合并用户自定义属性,默认属性
        var options = $.extend(defaults, options);
        //step4 支持JQuery选择器
        //step5 支持链式调用
        return this.each(function () {
            //step06-b 在插件里定义方法
            showLink(this);
        });
    }
})(jQuery);
View Code

八 经典实例练习

实例之注册验证  nbsp;在js中表示空格

<form action="" id="Form">
    用户名:<input type="text" name="username" class="con" mark="用户名"><br>
    密码&nbsp;:<input type="password" name="pwd" class="con" mark="密码"><br>
    <input type="submit" value="submit">
</form>



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

    $("#Form :submit").click(function(){
        var flag=true;
        $("#Form .con").each(function(){
              if ($(this).val().trim().length==0){
                  var span=$("<span>");
                  var mark=$(this).attr("mark");
                  span.text(mark+"不能为空");
                  $(this).after(span);
                  flag=false;
                  return false;//如果某个表单出现问题,马上提醒,有问题不能提交,下面的不能再判断
              }
        });
        return flag;//填写完,在提交前判断所有的表单,有问题不能提交
    });
</script>
<script>

        function f(){

        for(var i=0;i<4;i++){

            if (i==2){
                return
            }
            console.log(i)
        }

    }
    f();  // 这个例子大家应该不会有问题吧!!!
  结果为:1;2
//------------------------------------------ li=[11,22,33,44]; $.each(li,function(i,v){ if (v==33){ return ; // ===试一试 return false会怎样? } console.log(v) });   结果为:11;22;44 //------------------------------------------ // <1>如果你想return后下面循环函数继续执行,那么就直接写return或return true // <2>如果你不想return后下面循环函数继续执行,那么就直接写return false </script>


               
               
     

  

 

   

    

原文地址:https://www.cnblogs.com/domestique/p/6925386.html