初识jquery

玩转Jquery

一 jquery简介

1.jquery是什么? 

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

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 对象
View Code

3 jquery和js的区别是什么

jquery是用js写的,js是基础,jquery是工具

4 

jQuery知识点 html:裸体的人  css:穿了衣服的人  JS:让人动起来

2 jquery选择器

1、基本选择器
- ID选择器 // $("#id的值") - 类选择器(class// $(".class的值") - 标签选择器(html标签) // $("标签的名字") - 所有标签 // $("*") - 组合选择器 // $("xx,xxx") 2、层级选择器 - 从一个标签的子子孙孙去找 //$("父亲 子子孙孙") - 从一个标签的儿子里面找 // $("父亲>儿子标签") - 找紧挨着的标签 // $("标签+下面紧挨着的那个标签") - 找后面所有同级的 // $("标签~兄弟")
.3 基本筛选器 $("li:first") $("li:last") $("li:eq(2)")//索引 $("li:lt(3)")//<3索引的 4 属性选择器 $('["alex="sb"]) $("[alex]") 5表单选择器 $("[type='button']")==$(":button")// 必须是input标签才可以这样简写

 

2.2 筛选器

1.过滤筛选器

$("li").eq(2)         $("li").first()          $("ul li").hasclass("test")  //class==text 返回Ture

2 .查找筛选器

$("div").children(".test")   $("div").find(".test")  //只找儿子 找所有

$(".test").next()    $(".test").nextAll()    $(".test").nextUntil(6)    //下一个  所有兄弟  当前到第6(不包括6)

$("div").prev()      $("div").prevAll()       $("div").prevUntil()               //上一个

$(".test").parent()  $(".test").parents()     $(".test").parentUntil() //外层找
$("div").siblings()                                                                     //所有兄弟

三   操作元素(属性 CSS 和 文档处理) 

1 。属性操作

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

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

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

$(".test").prop("checked",true)    //涉及布尔值的用prop

$(".test").addClass("hide")

 2. css样式

样式
 css("{color:'red',backgroud:'blue'}")
位置
   $(window).scrollTop(0)

  $("body").scrollTop():滑动轮距离顶部的高度

   offset().top 标签距离文档顶部的高度
    height() 永远获取标签自身的高度
    innerHeight() 获取自己高度+pading(包括补白 包括内边距 不包    
    括边框)
    outHeigh()  获取自己高度+pading+boder+minger(参数设置为        
    Ture) 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-2.1.4.min.js"></script>
    <style>
       .menu{
           position:absolute;top:48px;left:200px;bottom:0;width:200px;background-color:#425a66;border:1px
       }
        .fafafa{
            position: fixed;top: 0;
        }
        #menu a{
            display: block;
        }
        .active{
            background-color: #204982;
            color: white;
        }

    </style>
</head>
<body style="margin: 0" onscroll="func1()">
<div style="height:48px;background-color: #204982;"></div>
<div  id="menu" class="menu">
    <A b="1">菜单一</A>
    <A b="2">菜单二</A>
    <A b="3">菜单三</A>
    <A b="4">菜单四</A>
</div>
<div id="content" style=position:absolute;top:48px;left:400px;right:200px;bottom:0;background-color:#b4b4b4;>
   <div id="li1"  a="1" style="height: 500px; background-color: #b4b4b4" ></div>
    <div id="li2" a="2" style="height: 900px; background-color: #204982"></div>
    <div id="li3" a="3" style="height: 1000px; background-color: #cc3399"></div>
    <div id="li4" a="4" style="height: 500px; background-color: #84a42b"></div>

</div>
<div onclick="func2()"; style="cursor:pointer;   width: 50px; height: 50px; background-color: #c0cddf; position: fixed; right: 0 ; bottom: 0" ></div>
<script>

    function  func2(){
        $(window).scrollTop(0);

    }



    function func1() {
    // var scroHeight=document.documentElement.scrollTop||document.body.scrollTop;
    var scroHeight=$(window).scrollTop();
    if(scroHeight >= 48 ){
          $('#menu').addClass('fafafa');

        }else {
                $('#menu').removeClass('fafafa');
                $("#menu a[b='1']").removeClass("active")
            }

       $('#content').children().each(function () {
           var ele=$(this).offset().top;
           var any=$(this).height()+ele-scroHeight;
           var docuheight=$(document).height();
           var wdheight=$(window).height();
           if (docuheight-wdheight==scroHeight){

               $('#menu a:last').addClass("active").siblings().removeClass("active")

           }
           else {
               if (ele-scroHeight<=0 && any>0){
                   var  qq= $(this).attr("a");//获取 a的值
                   $('#menu a[b="'+qq+'"]').addClass("active").siblings().removeClass("active")
           }
           }
       }
       )

    }


</script>
</body>

</html>
拖动滑轮,返回顶部

 

3. 文档处理

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

                   prepend()    prependTo()

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

         replaceWith()   remove()  empty()  clone()//复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.js"></script>
</head>
<body>
<div class="div1">
    <div>
        <input type="button" value="+" onclick="func1(this)" >
        <input type="text">
    </div>

</div>

<script>
    function func1(self) {
        var ele=$(self).parent().clone();
        ele.children(":button").attr("onclick","func2(this)");
        ele.children(":button").val("-");
        $(".div1").append(ele)
    }
    function func2(self) {
        $(self).parent().remove();

    }


</script>


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

   // $("#title").mouseover(function () {
   //     $(this).css("cursor","move" )
   // }).mousedown(function (event) {
   //     var old_x=event.screenX;
   //     var old_y=event.screenY;
   //
   //    var oldp_x=$(this).parent().offset().left;
   //     var oldp_y=$(this).parent().offset().top;
   //
   //     // $(this).mousemove(function (e)
   //     $(this).on("mousemove",function (e) {
   //     var new_x=e.screenX;
   //     var new_y=e.screenY;
   //
   //     var new_parent_x=oldp_x+(new_x-old_x);
   //     var new_parent_y=oldp_y+(new_y-old_y);
   //
   //     $(this).parent().css("top",new_parent_y+"px");
   //     $(this).parent().css("left",new_parent_x+"px")
   //
   //     }).mouseup(function () {
   //          $(this).off("mousemove")
   //
   //     })
   //
   // });


    $("#title").mouseover(function () {
          $(this).css("cursor","move")
      }).mousedown(function (event) {
           var start_x=event.screenX;
           var start_y=event.screenY;

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

          $(this).on("mousemove",function (e) {
               var new_x=e.screenX;
               var new_y=e.screenY;


              var new_parent_x=parent_left+(new_x-start_x);
              var new_parent_y=parent_top+(new_y-start_y);


              $(this).parent().css("left",new_parent_x+"px");
              $(this).parent().css("top",new_parent_y+"px");
          }).mouseup(function () {
              $(this).off("mousemove")
          })
      })


</script>
</body>
</html>
拖动面板

 

4 事件

1.head
   $(document).ready(function(){}) -----------> $(function(){})
2.body
   $("p").click(function(){})
   $("p").bind("click",function(){})    
   $("ul")on("clock","li","function(){}") //动态添加标签绑定方式

5 扩展

 jquery.extend({})  
 jquery.fn.extend({})

三   知识点总结

attr // prop

attr(属性名|属性值) - 一个参数是获取属性的值,两个参数是设置属性值

- 点击加载图片示例

removeAttr(属性名) 删除属性的值

prop(属性名|属性值) - 属性的返回值的是布尔类型

- 单选,反选,取消的例子

removeProp(属性名)-删除属性的值

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

             function selectall(){

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

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

             function reverse(){


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

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

                 });



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

             }

    </script>
</head>
<body>

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

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



</body>
</html>
正反选prop
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab</title>
    <script src="jquery-3.3.1.js"></script>
   
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
            width: 60%;
        }
        .menu{
            background-color: #cccccc;
            /*border: 1px solid red;*/
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
        }
        .menu a{
            border-right: 1px solid red;
            padding: 11px;
        }
        .content{
            background-color: tan;
            border: 1px solid green;
            height: 300px;
        }
        .hide{
            display: none;
        }

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

      </div>
<script>
    function tab(self) {
        $(self).addClass("current").siblings().removeClass("current")

        var s=$(self).attr("xxx");
        $("#"+s).removeClass("hide").siblings().addClass("hide")

    }


</script>
</body>
</html>
tab attr

 

循环

$.each(数组/对象, function(i, v){})

$("bable tr ").each(function(){})

//    方式一
    li = [11,22,33];
    $.each(li,function (i,v) {
        console.log(i,v)// 0 11
                         // 1 22
                         // 2 33
    })
//    方式二
    $(".c1").each(function (i,v) {
        console.log(i,v)  //这里的v拿到的是标签
//         0 <div class="c1">hah</div>
//         1 <div class="c1">年</div>
//         2 <div class="c1">娃的</div>
        console.log(v.innerText)  //拿到文本
    })
</script>
View Code

 

Css类

 - addClass 添加类属性
 - removeClass 移除类属性
 - toggleClass 开关|切换(有就移除,没有就添加)

HTML代码/文本/值

 没有参数就是获取对应的值,
        有参数就设置对应的值
        - .html()  添加html标签    .html("<span>啦啦啦。</span>")
        - .text()  添加文本        .text("啦啦啦。")
        - .val()
            input :一个参数,获取的是input框里面的值
            checkbox :一个参数,获取的是value的值
            select :
                单选:获取值
                多选:得到的是一个数组,设置的时候也要是数组
View Code

 

动画效果

1 显示隐藏

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>
    <STYLE>
        div{
            display: none;
        }
    </STYLE>
</head>
<body>

<p style="display: none">123</p>

<div  style= " background-color: #cc3399;width: 300px;height: 300px "></div>
<input id="show" type="button" value="显示">
<input id="hide" type="button" value="隐藏">
<input id="toggel" type="button" value="切换">

<script>
    $("#show").click(function () {
        $("div").show(2000, function f() {
            
        })

    });
     $("#hide").click(function () {
        $("div").hide(2000)

    });
     $("#toggel").click(function () {
        $("div").toggle(2000)
    })


</script>

</body>
</html>
显示隐藏,渐入渐出

2 淡入淡出

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>
    <STYLE>
        div{
            display: none;
        }
    </STYLE>
</head>
<body>

<p style="display: none">123</p>

<div  style= " background-color: #cc3399;width: 300px;height: 300px "></div>
<input id="in" type="button" value="显示">
<input id="out" type="button" value="隐藏">
<input id="toggel" type="button" value="切换">
<input id="fadeto" type="button" value="切换">

<script>
    $("#in").click(function () {
        $("div").fadeIn(2000, function f() {

        })

    });
     $("#out").click(function () {
        $("div").fadeOut(2000)

    });
     $("#toggel").click(function () {
        $("div").fadeToggle(2000)
    })
    $("#fadeto").click(function () {
        $("div").fadeTo(1000,0.5)
    })


</script>

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

3 滑入画出

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(){
  //    $("#flipshow").click(function(){
  //        $("#content").slideDown(1000);
  //    });
  //     $("#fliphide").click(function(){
  //        $("#content").slideUp(1000);
  //    });
  //     $("#toggle").click(function(){
  //        $("#content").slideToggle(1000);
  //    })
  // });
    </script>
    <style>
        #flipshow,#content,#fliphide,#toggle{
            /*padding: 5px;*/
            line-height: 30px;
            text-align: center;
            background-color: blueviolet;
            border:solid 1px red;

        }
        #content{
            padding: 50px;
            display: none;
        }
    </style>
</head>
<body>

    <div id="flipshow">出现</div>
    <div id="fliphide">隐藏</div>
    <div id="toggle">toggle</div>

    <div id="content">helloworld</div>
<script>
    $("#flipshow").click(function () {
          $("#content").slideDown(1000)
    });
    $("#fliphide").click(function () {
          $("#content").slideUp(1000)
    });
    $("#toggle").click(function () {
          $("#content").slideToggle(1000, function f() {
              alert("123")

        })
    })

</script>

</body>
</html>
滑入滑出

 

 表格技巧

 1 循环当前编辑标签的一行,添加到修改表单的默认val

   $(this).parent().prevAll().each(function () {
                var v=$(this).text();
                var n=$(this).attr('na');

                if(n=='cs_id'){
                    var cid=$(this).attr("cid");
                    $("#ediModal select[name='nid']").val(cid)
                }else if(n=='gender') {

                     if (v=='True'){
                         $("input[name='gender'][value='1']").prop("checked",true)
                     }else {$("input[name='gender'][value='0']").prop("checked",true)}
                } else {
                   $('#ediModal input[name='+n+']').val(v)

              }

          })
//利用列表循环,获取父亲兄弟,每一个text和na属性,  把input标签中name=当前标签属性 na的text设置为val值 $('#ediModal input[name='+n+']').val(v)

2 修改表单,获取输入表单的值,通过ajax提交

  var da_data={};
 $("#ediModal").find('input,select').each(function () {

                   var n=$(this).attr("name");
                   var v=$(this).val();

                   if(n=="gender"){
                        if ($(this).prop("checked")){
                      da_data[n]=v;
                        }
                   }
                   else {  da_data[n]=v   }

                });
//寻找 ediModal标签下面为input和select标签的 的循环,首先拿到当前
//    循环 name属性的值,  再拿到当前标签的val 
// 如果name=gender 如果当前标签的checked是Ture 那么字典的N等于
// 当前为Ture的值
//eles 字典的键==值

3 删除

   function bindDel() {
        $("#tb").on('click',".delrow",function () {

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

           var nid= $(this).parent().parent().attr("nid");

            $("#delnid").val(nid);
        })
    }
//给点击的标签绑定一个时间委托,找到当前删除标签的nid ,给隐藏的input标签添加为值

4 删除

function bindDelconfirm(){
        $("#delconfirm").click(function () {

            var id=$("#delnid").val();

            $.ajax({
                url: "/delstudents/",
                type: "POST",
                data: {"nid":id},
                success:function (arg) {

                    var data=JSON.parse(arg);
                    if (data.status){
                        $("tr[nid="+id+"]").remove();
                         $("#defModal").modal("hide");
                    }
                }

            })
        })
    }// 获取需要删除的id, 发送给后端

 

各种高度

  $(window).scroll(function () {
            console.log(1)
        })
滚轮滚动的时候执行

滑轮滚动 瀑布流 函数方式实现

 <script>

    $(function () {
        eachs();
        scrollEvent()
    });
    NID=0;
    lastpostion=3;
    function eachs() {

        $.ajax(
            {
                url:"/aa.html/",
                type:'GET',
                {#data:{'nid':NID},#}
                dataType:"JSON",
                success:function (data) {
                    var datas=data.data;
                //循环 data i代表索引 v代表valul
                    $(datas).each(function (i,v) {
                        var eqa=(i+lastpostion+1) % 4;
                //求余,分四列 0,1,2,3,如果一共五张图,第二行余下3个空,第二次循环需要从第二行,第二列开始,又因为当前的i(0)+lastpostion最后等于5,应该在第六个开始,所以加1, 
最后因为第一次循环第一张图放到第二个位置, 所以把lastpostion设置为3 这样3+1=0, 就会放到第一个位置
console.log(eqa) var tag=document.createElement('img'); tag.src='/'+v.student__pic; tag.style.height=500+'px'; $(".content_body").children().eq(eqa).append(tag); //父亲寻找孩子的第几个元素添加 tag ,上面eqa已经求出余数,所以可以这样添加 if (i+1 == datas.length){ NID=v.student__id; //如果索引+1 = 列表的长度,那么把nid设置为当前id lastpostion = eqa // lastpostion 设置为最后一次余数的位置 } }) } } ) } function scrollEvent() { $(window).scroll(function () { //文档总高度 var docHeight = $(document).height(); //窗口高度 var winHeight = $(window).height(); // 滑轮滚动高度 var scro = $(window).scrollTop(); console.log(docHeight,winHeight,scro); //如果窗口高度+滑轮滚动高度=总高度(意味着滑轮到底,执行以下代码) if (winHeight+ scro ==docHeight){ eachs() } }) } </script>

 面向对象方式实现

    $(function () {
        var obj =new Scroimg();
        obj.eachs();
        obj.scrollEvent();
    })

      function Scroimg(){
            this.NID=0;
            this.lastpostion=3;
            this.eachs=function () {
                var that=this;
                 $.ajax(
                {
                url:"/aa.html/",
                type:'GET',
                data:{'nid':that.NID},
                dataType:"JSON",
                success:function (data) {
                    var datas=data.data;
                    $(datas).each(function (i,v) {
                        var eqa=(i+that.lastpostion+1) % 4;
                        console.log(eqa);
                        var tag=document.createElement('img');
                        tag.src='/'+v.student__pic;
                        tag.style.height=500+'px';
                        $(".content_body").children().eq(eqa).append(tag);

                        if (i+1 == datas.length){
                            that.ID=v.student__id;

                            that.lastpostion = eqa


                                        }
                                })
                            }
                        }
                    )

                };

            this.scrollEvent=function () {
                var that=this;

                $(window).scroll(function () {
                    //文档总高度
                    var docHeight = $(document).height();
                    //窗口高度
                    var winHeight = $(window).height();
                    //
                    var scro = $(window).scrollTop();

                    console.log(docHeight,winHeight,scro);

                    if (winHeight+ scro ==docHeight){
                        that.eachs()
                    }

            })



             };
        }
面向对象实现

 

posted @ 2018-12-12 20:07  new边城  阅读(56)  评论(0)    收藏  举报