jQuery基礎學習

来源:https://www.cnblogs.com/mayi0312/archive/2019/07/10/11161747.html
-Advertisement-
Play Games

jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是“Write Less, Do More”,即倡導寫更少的代碼,做更多的事情。它封裝JavaScript常用的功能代碼,提供... ...


一、簡介

  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>

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 第0步:版本選擇 AOSP版本選擇很重要,如果選錯了,會造成編譯失敗等各種問題,編譯AOSP對Xcode的版本是有要求的; 比如:AOSP6.0 7.0,要求Xcode的版本是8.3,然而在MacOS 10.14上面是不支持Xcode8.3的這就很尷尬; 由於現在大家的Mac環境基本是更新到最新的1 ...
  • 在Dart裡面,變數的聲明使用var、Object或Dynamic關鍵字,如下所示: var name = ‘張三’; 在Dart語言里一切皆為對象,所以如果沒有將變數初始化,那麼它的預設值為null(包括數字),如果需要判斷變數是否為null,則需要進行如下判斷: String name;if(n... ...
  • iOS查看屏幕幀數工具--YYFPSLabel iOS 保持界面流暢的技巧 iOS 優化界面流暢度的探討 先研究一下 改天自己出一篇文章 ...
  • 原文:https://www.jianshu.com/p/b5a484cecd7c 本文主要說明2018年蘋果開發者賬號申請的流程,申請流程相較於2017年有一些改變,希望大家能夠通過本文少走一些彎路,能夠順利完成開發者賬號的申請。關於新流程中可能出現的一些問題以及部分流程的變更均在下文中運用灰色塊 ...
  • 一、數據綁定 二、列表渲染 <!--index.wxml--> 三、綁定一個點擊事件 四、事件冒泡 五、事件傳參 ...
  • 系統自帶的分段選擇就是 UISegmentedControl ,也有一些大佬自定義的 Segmented ,比如Git上的 HMSegmentedControl ,我以前最初的項目中,也有用到過,如果自己寫,或者想自定義一些UI,該從哪裡出發,其實在用過 HMSegmentedControl 之後, ...
  • 第一步:手機連接到itunes 選擇本電腦備份 備份的時候不要加密 然後立即備份 第二步:前往文件夾,找到itunes的備份路徑~/Library/Application Support/MobileSync/Backup 在這目錄下搜索 3d0d開頭的文件,這就是 iPhone 簡訊的資料庫文件。 ...
  • 目前iOS組件化常用的解決方案是Pod+路由+持續集成,通常架構設計完成後第一步就是將原來工程里的模塊按照架構圖分解為一個個獨立的pod工程(組件),今天我們就來看看如何創建一個Pod私有庫。 新建:pod lib create 假設我們需要創建的庫名為TestLib,下麵我們使用Pod官方提供的創 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...