当前位置: 移动技术网 > IT编程>开发语言>Jquery > jQuery基础学习

jQuery基础学习

2019年07月10日  | 移动技术网IT编程  | 我要评论

一、简介

  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是什么?

  ·jquery是由美国人john resig创建,至今已吸引了来自世界各地的众多javascript高手加入其中。

  ·jquery是继prototype之后又一个优秀的javascript框架。其宗旨是——write less, do more!

  ·jquery是轻量级的js库,这是其它的js库所不及的,它兼容css3,还兼容各种浏览器。

  ·jquery是一个快速的,简洁的javascript库,使用户能更方便地处理html documents、events、实现动画效果,并且方便地为网站提供ajax交互。

  ·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()

四、寻找元素(选择器和筛选器)

4.1 选择器

  4.1.1 基本选择器

$("*")

$("#id")

$(".class")

$(".class, p, div")

  4.1.2 层级选择器

$(".outer div")

$(".outer>div")

$(".outer+div")

$(".outer~div")

  4.1.3 基本筛选器

$("li:first")

$("li:eq(2) ")

$("li:even")

$("li:gt(1) ")

  4.1.4 属性选择器

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

$('[name="mayi"]')

  4.1.5 表单选择器

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

  4.1.6 表单属性选择器

:enabled

:disabled

:checked

:selected

  例子:

<body>
<form>
    <label>123<input type="checkbox" value="123" checked /></label>
    <label>456<input type="checkbox" value="456" checked /></label>

    <label>植物
        <select>
            <option value="1">flowers</option>
            <option value="2">garends</option>
            <option value="3">trees</option>
        </select>
    </label>
</form>

<script src="jquery-3.4.1.js"></script>
<script>
    // console.log($("input:checked").length); //2

    $("input:checked").each(function(){
        console.log($(this).val())
    })
</script>
</body>

4.2 筛选器

  4.2.1 过滤筛选器

$("li").eq(2)

$("li").first()

$("ul li").hasclass("test")

  4.2.2 查找筛选器

查找子标签

$("div").children(".test");

$("div").find(".test");

向下查找兄弟标签

$(".test").next();

$(".test").nextall();

$(".test").nextuntil();

向上查找兄弟标签

$("div").prev();

$("div").prevall();

$("div").prevuntil()

查找所有兄弟标签

$("div").siblings()

查找父标签

$(".test").parent();

$(".test").parents();

$(".test").parentuntil();

五、操作元素(属性、css、文档处理)

5.1 事件

  页面载入

ready(fn);  //当dom载入就绪可以查询及操作时绑定一个要执行的函数。
$(document).ready(function(){}); //-----> $(function(){})  

  事件绑定

//语法:标签对象.事件(函数)
$("p").click(function(){});

  事件委派

//在选择元素上绑定一个或多个事件的事件处理函数。
$("").on(eve, [selector], [data], fn);

  例子:

<body>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<hr>
<button id="add_li">add_li</button>
<button id="off">off</button>

<script src="jquery-3.4.1.js"></script>
<script>
    $("ul li").click(function(){
        alert(123);
    });

    $("#add_li").click(function(){
        var $ele = $("<li>");
        $ele.text(math.round(math.random() * 10));
        $("ul").append($ele);
    });

//    $("ul").on("click", "li", function(){
//        alert(456);
//    });

    $("#off").click(function(){
        $("ul li").off();
    });

</script>
</body>

  事件切换

  hover事件:一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态。

  over事件:鼠标移到元素上要触发的函数。

  out事件:鼠标移出元素要触发的函数。

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test03</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .test {
            width: 200px;
            height: 200px;
            background-color: wheat;
        }
    </style>
</head>
<body>
<div class="test"></div>

<script src="jquery-3.4.1.js"></script>
<script>
//    function enter(){
//        console.log("enter");
//    }
//
//    function out(){
//        console.log("out");
//    }
//
//    $(".test").hover(enter, out);

    $(".test").mouseenter(function(){
        console.log("enter");
    });

    $(".test").mouseleave(function(){
        console.log("leave");
    })

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

5.2 属性操作

//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方法使用:

<body>
<label><input id="chk1" type="checkbox" />是否可见</label>
<label><input id="chk2" type="checkbox" checked="checked" />是否可见</label>
<script src="jquery-3.4.1.js"></script>
<script>
    //对于html元素本身就带有的固有属性,在处理时,使用prop方法。
    //对于html元素我们自定义的dom属性,在处理时,使用attr方法。
    //像checkbox, radio和select这样的元素,选中属性对应“checked”和“selected”,这
    // 些也属于固有属性,因此需要使用prop方法去操作才有获得正确的结果。

    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>
</body>

5.3 each循环

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

  jquery支持两种循环方式:

  方式一:

  格式:$.each(obj, fn)

li = [10, 20, 30, 40];
dic = {name: "mayi", sex: "male"};

$.each(li, function(i, x){
    console.log(i, x);
});

$.each(dic, function(k, v){
    console.log(k, v);
});

  方式二:

  格式:$("").each(fn)

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

  其中,$(this)代指当前循环标签。

5.4 文档节点处理

  创建一个标签对象

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

$("p").before("<b>hello</b>");

 

 

$("").insertafter(content|fn)

$("p").insertafter("#foo");

 

 

$("").insertbefore(content)

$("p").insertbefore("#foo");

 

 

  替换

$("").replacewith(content|fn)

$("p").replacewith("<b>paragraph.</b>");

  删除

$("").empty()

$("").remove([expr])

  复制

$("").clone([even[, deepeven]])

5.5 动画效果

  显示隐藏

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
</head>
<body>
<p>hello</p>
<button id="hide">隐藏</button>
<button id="show">显示</button>
<button id="toggle">切换</button>

<script src="jquery-3.4.1.js"></script>
<script>
    $("#hide").click(function(){
        $("p").hide(1000);  //1000毫秒
    });

    $("#show").click(function(){
        $("p").show(1000);  //1000毫秒
    });

    $("#toggle").click(function(){
        $("p").toggle(1000);  //1000毫秒
    });
</script>
</body>
</html>

  滑动

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
    <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">切换</div>
<div id="content">hello world!</div>

<script src="jquery-3.4.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>
</body>
</html>

  淡入淡出

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
    <style>
        #id1 {
            display: none;
            width: 80px;
            height: 80px;
            background-color: blueviolet;
        }
    </style>
</head>
<body>
<button id="in">fade in</button>
<button id="out">fade out</button>
<button id="toggle">fade toggle</button>
<button id="to">fade to</button>
<div id="id1"></div>

<script src="jquery-3.4.1.js"></script>
<script>
    $("#in").click(function(){
        $("#id1").fadein(1000);
    });

    $("#out").click(function(){
        $("#id1").fadeout(1000);
    });

    $("#toggle").click(function(){
        $("#id1").fadetoggle(1000);
    });

    $("#to").click(function(){
        $("#id1").fadeto(1000, 0.4);
    });

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

  回调函数

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
</head>
<body>
<button>hide</button>
<p>hello world</p>
<script src="jquery-3.4.1.js"></script>
<script>
    $("button").click(function(){
        $("p").hide(1000, function(){
            alert($(this).html());
        });
    });

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

5.6 css操作

  css位置操作

$("").offset([coordinates])
$("").position()
$("").scrolltop([val])
$("").scrollleft([val])

  示例1:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
    <style>
        .test {
            width: 200px;
            height: 200px;
            background-color: wheat;
        }
    </style>
</head>
<body>
<h1>this if offset</h1>
<div class="test"></div>
<p></p>
<button>change</button>

<script src="jquery-3.4.1.js"></script>
<script>
    var $offset = $(".test").offset();
    var $lefts = $offset.left;
    var $tops = $offset.top;

    $("p").text("top:" + $tops + " left:" + $lefts);
    $("button").click(function(){
        $(".test").offset({left: 200, top: 400});
    });

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

  示例2:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
    <style>
        * {
            margin: 0;
        }

        .box1 {
            width: 200px;
            height: 200px;
            background-color: rebeccapurple;
        }

        .box2 {
            width: 200px;
            height: 200px;
            background-color: darkcyan;
        }

        .parent_box {
            position: relative;
        }
    </style>
</head>
<body>
<div class="box1">hello box1</div>
<div class="parent_box">
    <div class="box2">hello box2</div>
</div>
<p>hello p</p>

<script src="jquery-3.4.1.js"></script>
<script>
    var $position = $(".box2").position();
    var $left = $position.left;
    var $top = $position.top;

    $("p").text("top:" + $top + " left:" + $left);

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

  示例3:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
    <style>
        body {
            margin: 0;
        }

        .returntop {
            height: 60px;
            width: 100px;
            background-color: peru;
            position: fixed;
            right: 0;
            bottom: 0;
            color: white;
            line-height: 60px;
            text-align: center;
        }

        .div1 {
            background-color: wheat;
            font-size: 5px;
            overflow: auto;
            width: 500px;
            height: 200px;
        }

        .div2 {
            background-color: darkgray;
            height: 2400px;
        }

        .hide {
            display: none;
        }
    </style>
</head>
<body>
<div class="div1 div">
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
</div>
<div class="div2 div">hello div2</div>
<div class="returntop hide">返回顶部</div>

<script src="jquery-3.4.1.js"></script>
<script>
    $(window).scroll(function(){
        var $current = $(window).scrolltop();
        console.log($current);
        if($current > 100){
            $(".returntop").removeclass("hide");
        }
        else{
            $(".returntop").addclass("hide");
        }
    });

    $(".returntop").click(function(){
        $(window).scrolltop(0);
    });

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

  css尺寸操作

$("").height([val|fn])
$("").width([val|fn])
$("").innerheight()
$("").innerwidth()
$("").outerheight([soptions])
$("").outerwidth([options])

示例:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>test</title>
    <style>
        * {
            margin: 0;
        }

        .box1 {
            width: 200px;
            height: 200px;
            background-color: wheat;
            padding: 50px;
            border: 50px solid rebeccapurple;
            margin: 50px;
        }
    </style>
</head>
<body>
<div class="box1">
    hello div
</div>
<p>hello p</p>

<script src="jquery-3.4.1.js"></script>
<script>
    var $ele = $(".box1");
    var $height = $ele.height();
    var $innerheight = $ele.innerheight();
    var $outerheight = $ele.outerheight();
    var $margin = $ele.outerheight(true);

    //200---300---400---500
    $("p").text($height + "---" + $innerheight + "---" + $outerheight + "---" + $margin);

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

六、扩展方法(插件机制)

6.1 jquery.extend(object)

  扩展jquery对象本身。

  用来在jquery命名空间上增加新函数。

  例:在jquery命名空间上增加两个函数:

<script src="jquery-3.4.1.js"></script>
<script>
    jquery.extend({
        min: function(a, b) { return a < b ? a : b;},
        max: function(a, b) { return a > b ? a : b;}
    });

    console.log(jquery.min(2, 3));  //2
    console.log(jquery.max(4, 5));  //5
</script>

6.2 jquery.fn.extend(object)

  扩展jquery元素集来提供新的方法(通常用来制作插件)。

  例:增加两个插件方法:

<body>
<label><input type="checkbox" /></label>
<label><input type="checkbox" /></label>
<label><input type="checkbox" /></label>

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

    $(":checkbox:gt(0)").check();

</script>
</body>

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网