首页 > 技术文章 > jQuery 基础知识

eric_yi 原文

一、序言

  jQuery是一个快速、简洁的JavaScript框架,是继Prototype之后的又一个优秀的JavaScript代码库(JavaScript框架)。jQuery设计的宗旨是"Write Less, Do More",即倡导写更少的代码,做更多的事情。它封装JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和AJAX交互。
  jQuery的核心特性可以总结为:具有独特的链式语法和短小清晰的多功能接口;具有高效灵活的CSS选择器,并且可对CSS选择器进行扩展;拥有便捷的插件扩展机制和丰富的插件。

二、jQuery对象

  Query对象就是通过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).acttion()

三、jQuery框架分类

  •  核心
  •  选择器
  •  属性
  • CSS
  • 文档处理
  • 筛选 
  • 效果
  • 事件
  • 事件对象
  • 延迟对象
  • 回调函数
  • AJAX
  • 工具

四、选择器

4.1 基本选择器

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

4.2 层级选择器

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

4.3 基本筛选器

$("li:fister")  $("li:eq(2)")   $("li:even")    $("li:gt(1)")

4.4 属性选择器

$('[id="div1"]')    $('[name="abc"[id]]')

4.5 表单选择器

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

4.6 表单属性选择器

 :enabled
 :disabled
 :checked
 :selected

五、筛选器

5.1 过滤筛选器

$("li").eq(2)   $("li").first() $("ul li").hasclass("test")

5.2 查找筛选器

   // 查找子标签:
$("div").childred(".test");
$("div").find(".test");

    //向下查找兄弟标签:
$(".test".next());  
$(".test".nextAll();
$(".test").nextUntil();

    //向上查找兄弟标签:
$("div").prev();   
$("div").prevAll();
$("div").prevUntil();

    //查找所有兄弟标签:
$("div").siblings();

    //查找父标签:     
$(".test").parent();     
$(".test").parents();
$(".test").parentUntil();

六、 事件

//页面载入
read(fn)    //到DOM载入就绪可以查询及操作时绑定一个要执行的函数
#(document).ready(function(){}  //也可以写成 $(function(){}    文档就绪事件

//事件绑定
//语法:标签对象.事件(函数) eg:$("p").click(function(){}) //事件委派 $("").on(eve,[selector],[data],fn) //在选择元素上绑定一个或多个时间处理函数 //事件切换 hover :一个模仿悬停事件(鼠标移动到一个对象上面及移除这个对象)的方法。这个一个自定义的方法,它为频繁使用的任务提供了一种"保持在其中“de ”的状态 over:鼠标移到元素上要触发的函数 out:鼠标移除元素要触发的函数

七、 属性操作

    //CSS类
    $("").addClass(class|fn)
    $("").removeClass([class|fn])

    //属性
    $("").attr();
    $("").removeAttr();
    $("").prop();
    $("").removeProp();

    //HTML代码/文本/值
    $("").html([val|fn])
    $("").text([val|fn])
    $("").val([val|fn|arr])
    $("#c1").css({"color":"red", "fontSize":"35px"})

    //attr使用方法:
    <input id="chk1" type="checkbox" />
    <input id="chk2" type="checkbod" 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>

八、 工具-each循环

我们知道
$("p").css("color","red")
是将css操作加到所有的标签上,内部维持一个循环;但如果对于选中标签就行不同处理,这时就需要
对所有标签数组就行循环遍历

    //jQuery支持两个循环方式:
    //方式1:
    $.each(obj,fn)
    arr = [10, 20, 30, 40];
    dic = {name:"abc", sex:"male"};
    $.each(arr, function(i,x){
        console.log(i,x)
    })

    //方式2://$(this)指当前循环标签
    $("").each(fn)
    $("tr").each(function(){
        console.log($(this).html())
    })

九、 文档节点处理

    //创建一个标签对象
    $("<p>")

    //内部插入
    $("").append(content|fn)   --->$("p").append("<b>Helo</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").repalceWith("<b>Paragraph.</b>");

    //删除
    $("").empty()
    $("").remove([expr])

    //复制
    $("").clone([Even[,deepEven]])

十、动画效果

//显示隐藏
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquest.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>

        <link type="text/css" rel="stylesheet" href="style.css">
    </head>
    <body>
        <p>hello<p>
        <button id="hid">隐藏</button>
        <button id="show>显示</button>
        <button id="toggle">切换</button>
    </body>
    </html>
    滑动
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery.js"></script>
        <script>
            $(document).ready(function(){
                $("#slideDown").click(function(){
                    $("#content").slideDown(1000);
                });
                #("#slideUp").click(function(){
                    $("#content").slideUo(1000);
                });
                #("#slideToggle").click(function(){
                    $("#content").slideToggle(1000);
                })
            });
            <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>
        淡入淡出
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
            <script src="jquery.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);
                    });
                });
            </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: blue;</div>
        </body>
        </html>

十一、回调函数

    callbacks.add(callbacks)    回调列表中添加一个回调或回调的集合
    callbacks.disable()         禁用回调列表中的回调
    callbacks.empty()           从列表中删除所有回调
    callbacks.fire(arguments)   禁用回调列表中的回调
    callbacks.fired()           用给定的参数调用所有的回调
    callbacks.fireWith([c][,a]) 访问给定的上下文和参数列表中的所有回调
    callbacks.has(callback)     确定是否提供回调列表
    callbacks.lock()            锁定在其当前状态的回调列表
    callbacks.locked()          确定是否已被锁定的回调列表
    callbacks.remove(callbacks) 删除回调或回调列表的集合
    jQuery。callbacks(flags)
        一个多用途的回调列表对象,提供了强大的方式来管理回调函数列表。
        $.callback()的内部提供了jQuery的$.ajax()和$.Deferred()基本功能组件。它可以用来作为类似基础定义的新组件的功能。
        $.callbacks()支持的方法,包括callbacks.add(),callbacks.remove(),callbacks.fire(),callbacks.disable()

十二、CSS操作

//css位置操作
$("").offset([coordinates])
$("").positon()
$("").scrollTop)([val])
$("").scrollLeft)([val])

//尺寸操作
$("").height([val|fn])
$("").width([val|fn])
$("").innerHeight()
$("").innerWidth()
$("").outerHeight([options])
$("").outWidth([options])

十三、扩展方法(插件机制)

jQuery.extend(object)

//扩展jQuery对象本身
//用来在jQuery命名空间上增加新函数
//在jQuery命名空间上增加两个函数:
<script>
    jQuery.extent({
        min:function(a, b) {return a<b ? a:b;},
        max:function(a, b) {return a>b ? a:b;}
     });

    jQuery.min(2,3); //2
    jQuery.max(4,5); //5
</script>

jQuery.fn.extend(object)
//扩展jQuery元素集来提供新的方法(通常用来制作插件)
//增加两个两个插件方法:
<body>
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">

     <script src="jquery.js"></script>
     <script>
        jQuery.fn.extend({
            check: function(){
                $(this).attr("checked", true);
            },
            uncheck: function(){
                $(this).attr("shecked", false);
            },
        });

        $(":checkbox":gt(0).check()
     </script>
 </body>

 

推荐阅读