【学习笔记】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").html(); $("#msg")[0].innerHTML

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

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

1.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]')

表单选择器

$("[type='text']")----->$(":text")         注意只适用于input标签  : $("input:checked")

实例之左侧菜单

左侧为菜单,右侧为内容区,默认显示菜单一的内容,点击其他菜单会显示点击菜单的内容并隐藏其他菜单内容。

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>left_menu</title>

    <style>
          .menu{
              height: 500px;
              width: 30%;
              background-color: gainsboro;
              float: left;
          }
          .content{
              height: 500px;
              width: 70%;
              background-color: rebeccapurple;
              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">菜单一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title">菜单二</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title">菜单三</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>
           $(".item .title").click(function () {
                $(this).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");

//                $(this).next().removeClass("hide");
//                $(this).parent().siblings().children(".con").addClass("hide");
           })
</script>


</body>
</html>

1.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()

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

2.1 属性操作

--------------------------属性
$("").attr();
$("").removeAttr();
$("").prop();
$("").removeProp();
--------------------------CSS类
$("").addClass(class|fn)
$("").removeClass([class|fn])
--------------------------HTML代码/文本/值
$("").html([val|fn])
$("").text([val|fn])
$("").val([val|fn|arr])
---------------------------
$("").css("color","red")

注意:

对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。

对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。

像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果。

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

<script>
//    $("#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>

2.2 jquery循环的两种方式

方式一:对对象进行循环

li = [1,2,3,4]
$.each(li,function(i,x){
    console.log(i,x)
})

$.each(遍历的对象, function(下标, 取值))function里需要两个参数,一个是下标,一个是值

方式二:对DOM节点进行循环

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

jQuery对象.each(function(){}),在函数体里面,用$(this)来代表循环中的每一个对象。

实例之全反选

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

     <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 src="jquery-3.1.1.js"></script>
    <script>
        function selectall() {
            $(":checkbox").each(function () {
                $(this).prop("checked", true);
            })
        }
        function cancel() {
            $(":checkbox").each(function () {
                $(this).prop("checked", false);
            })
        }
        function reverse() {
            $(":checkbox").each(function () {
                $(this).prop("checked", !$(this).prop("checked"));
            })
        }
    </script>

实例之模态对话框

<!DOCTYPE html>
<html >
<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;
            width: 200px;
            background-color: gold;

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

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


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

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

    }
    function action2(self){
        // 方法一
        //$(self).parent().parent().children(".models,.shade").addClass("hide")
        
        // 方法二
        $(self).parent().addClass("hide").prev().addClass("hide")

    }
</script>
</body>
</html>

2.3 文档操作

创建一个标签对象

$("<p>")

内部插入:插入到标签内部

    $("").append(content|fn)      ----->$("p").append("<b>Hello</b>");
    $("").appendTo(content)       ----->$("p").appendTo("div");
    $("").prepend(content|fn)     ----->$("p").prepend("<b>Hello</b>");
    $("").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]])

实例之复制样式条

<!DOCTYPE html>
<html >
<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-3.1.1.js"></script>
    <script>
        function add(self) {
            // 注意:if var $clone_obj=$(".outer .item").clone();会一遍二,二变四的增加
            var $clone_obj = $(self).parent().clone();
            // 增加的同时改变所增加item中的value和onclick的函数
            $clone_obj.children(":button").val("-").attr("onclick","remove(this )");
            $(self).parent().parent().append($clone_obj)
        }

        function remove(self) {
            $(self).parent().remove();
        }
    </script>
</body>
</html>

2.4 CSS操作

    CSS
        $("").css(name|pro|[,val|fn])
    位置
        $("").offset([coordinates])
        $("").position()
        $("").scrollTop([val])
        $("").scrollLeft([val])
    尺寸
        $("").height([val|fn])
        $("").width([val|fn])
        $("").innerHeight()
        $("").innerWidth()
        $("").outerHeight([soptions])
        $("").outerWidth([options])

实例返回顶部

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.1.1.js"></script>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .div2{
            width: 100%;
            height: 2000px;
            background-color: rebeccapurple;
        }
        .div1{
            width: 100%;
            height: 1500px;
            background-color: antiquewhite;
            overflow: auto;
        }
        .returnTop{
            position: fixed;
            right: 20px;
            bottom: 20px;
            width: 90px;
            height: 50px;
            background-color: green;
            color: white;
            text-align: center;
            line-height: 50px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
    <div class="div1">
    </div>
    <div class="div2"></div>
    <div class="returnTop hide" onclick="returnTop()">返回顶部</div>
    <script>
        window.onscroll = function () {
          if($(window).scrollTop() > 300){
              $(".returnTop").removeClass("hide");
          }else{
              $(".returnTop").addClass("hide");
          }
        };
        function returnTop() {
            $(window).scrollTop(0);
        }
    </script>
</body>
</html>

三 事件

页面载入

  • ready(fn)

    当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。

  • $(document).ready(function(){}) -----------> $(function(){})

    页面加载完成之后自动执行。

事件处理

 $("").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)

实例之面板拖动

<!DOCTYPE html>
<html>
<head >
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div >
        <div  >
            标题
        </div>
        <div >
            内容
        </div>
    </div>
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<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).bind('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).unbind('mousemove');
        });
    })
</script>
</body>
</html>

四 动画效果

显示、隐藏

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

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

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

    </script>
</head>
<body>


    <p>hello</p>
    <button >隐藏</button>
    <button >显示</button>
    <button >切换</button>

</body>
</html>

滑动

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="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>

    <div >出现</div>
    <div >隐藏</div>
    <div >toggle</div>

    <div >helloworld</div>

</body>
</html>

淡入淡出

  1. <!DOCTYPE html>
  2. <html >
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <script src="jquery-3.1.1.js"></script>
  7. <script>
  8. $(document).ready(function () {
  9. $("#in").click(function () {
  10. $("#id1").fadeIn(1000);
  11. });
  12. $("#out").click(function () {
  13. $("#id1").fadeOut(1000);
  14. });
  15. $("#toggle").click(function () {
  16. $("#id1").fadeToggle(1000);
  17. });
  18. $("#fadeto").click(function () {
  19. $("#id1").fadeTo(1000, 0.4);
  20. });
  21. });

  22. </script>

  23. </head>
  24. <body>
  25. <button >fadein</button>
  26. <button >fadeout</button>
  27. <button >fadetoggle</button>
  28. <button >fadeto</button>

  29. <div ></div>

  30. </body>
  31. </html>

回调函数

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

五 扩展方法(插件机制)

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

  • $.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(object)

    为JQuery实例添加一个方法。

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

    }
});

$("p").print();

2 定义作用域

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

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

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

3 默认参数

定义了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);

六 实例之注册验证

提示用户名或者邮箱不能为空。

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form class="Form">

    <p><input class="v1" type="text" name="username" mark="用户名"></p>
    <p><input class="v1" type="text" name="email" mark="邮箱"></p>
    <p><input class="v1" type="submit" value="submit" onclick="return validate()"></p>

</form>

<script src="jquery-3.1.1.js"></script>
<script>
    // 注意:
    // DOM对象--->jquery对象    $(DOM)
    // jquery对象--->DOM对象    $("")[0]

    // DOM绑定版本
    function validate() {

        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>

参考:http://www.cnblogs.com/yuanchenqi/articles/6070667.html