jQuery初識
-
jq是一款用原生js封裝的,操作dom的類庫
- 他裏面封裝的大量的方法,基於這些方法,可以使我們快速的取操作dom和構建我們的項目
-
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+等。
- 推薦自學方法
- 1、jQuery相關API
- 2、用jQuery做案例
- 3、看源碼:可以提高你自己封裝插件的能力,也可以提高你閱讀其他代碼的能力
- 推薦自學方法
jQuery的語法
1、獲取dom的方式
- $(‘選擇器’) jq選擇器
- eq(索引) 找到索引對應的元素
- gt(索引) 找到大於索引對應的元素
- lt(索引) 找到小於索引對應的元素
- find(‘選擇器’) 找到對應的後代元素
- filter(‘選擇器’) 把符合條件的過濾出來
// 如果你是用jq獲取的東西,那變量接收時,那這個變量名前一般加上$,這時大家約定俗稱的規範,別人一看就知道你是用jq獲取的
let $box = $('#box')
$('.box li').eq(0)
$('.box li').gt(2)
$('.box li').lt(2)
$('.box').find('li').filter('.active')
2、節點之間的屬性
- prev() 獲取上一個哥哥元素
- prev(‘span’) 獲取標籤名爲span的哥哥元素
- prevAll() 獲取所有的哥哥元素
- next() 獲取下一個兄弟元素
- next(‘span’) 獲取下一個標籤名爲span的兄弟元素
- nextAll() 獲取所有的兄弟元素
- parent() 獲取父親元素
- parents() 獲取所有的祖先元素
$('.box').prev() // 獲取上一個哥哥元素
$('.box').prev('span') // 獲取上一個標籤名爲span的哥哥元素
$('.box').prevAll() // 獲取所有的哥哥元素
$('.box').next() // 獲取下一個兄弟元素
$('.box').next('span') // 獲取下一個標籤名爲span的兄弟元素
$('.box').nextAll()// 獲取所有的兄弟元素
$('.box').siblings() // 獲取所有的哥哥兄弟元素
$('.box').parent()
$('.box').parents() // 獲取所有的祖先元素,直到document
3、dom的增刪改
- $(’.box’).append(‘
333
’) // 往指定的元素末尾插入元素 - $(’.box’).html() // 獲取 innerHTML
- $(’.box’).html(‘2222’) // 設置
- $(’.box’).text() // 獲取 innerText
- $(’.box’).text(‘2222’) // 設置
div.html = '1111'
let $ss = $('.box').clone()
4、自定義屬性
$('.box').attr('data-time') // 獲取自定義屬性
$('.box').attr('data-time', 11) // 設置自定義屬性
$('.box').attr({
"data-type":1,
"data-time":2,
}) // 設置一組自定義屬性
$('.box').removeAttr('data-time') // 移除自定義屬性
5、css
$('.box').css('width') // 獲取css樣式
$('.box').css('width', 100) // 設置css樣式
$('.box').css({
width:100,
height:100
})
$('.box').addClass('active')
$('.box').removeClass('active')
$('.box').hasClass('active') // 檢測當前元素是否擁有當前的class名,如果有就是true,
沒有就是false
$('.box').toggleClass('active') // 自動判斷當前元素是否擁有這個class名,如果有就是刪除,
沒有就是增加
6、js盒子模型
$('.box').offset // 跟咱自己封裝的一樣的,距離body的上、左偏移量
$('.box').position // 獲取父級參照物
$('.box').innerHeight/innerWidth/outerHeight/outerWidth
clientHeight/ clientWidth/offsetHeight/offsetWidth
$(document).scrollTop
$(document).scrollLeft
7、工具、事件
box.onclick = fn
$('.box').on('eventType', fn) // 增加事件
$('.box').on('click', fn)
$('.box').click(fn)
$('.box').off('click', fn) // 移除事件
forEach
$('.box li').each(function(index, item){
// 可以遍歷數組,類數組,對象
//index是每一項的索引
// item是每一項
// 如果遍歷的是對象,那index是屬性名,item是屬性值
})
$('.box li').toArray()
$.uniqueSort()
8、如果是表單元素
$('input').val() // 獲取表單元素的內容
$('input').val('666') // 設置表單元素的內容
// html和text對錶單元素不起作用
9、表單元素的行內屬性
$('radio').prop('checked') // 獲取行內屬性
$('radio').prop('checked', true) // 設置行內屬性
$('radio').removeProp('checked') // 移除行內屬性
語法
1. jquery的選擇器
- $(‘選擇器’) jquery選擇器
<body>
<ul>
<li class="a">1</li>
<li>2</li>
<li>3</li>
</ul>
<div></div>
<div></div>
<div></div>
<input type="text" name="abcshd">
<input type="text" name="ab">
<input type="text" name="s">
<input type="text" name="a">
<script src="../../jquery-1.11.3.js"></script>
<script>
console.log($('li:first')); //獲取第一個li,放在一個數組裏
console.log($("li:not('.a')")); //獲取class名不叫a的li,放在一個數組裏
console.log($('li:even')); //獲取索引爲偶數的li,放在一個數組裏
console.log($('li:odd')); //獲取索引爲奇數的li,放在一個數組裏
console.log($('li:eq(1)')); //找到索引爲1的li,放在一個數組裏
console.log($('li:gt(1)')); //找到索引大於1的li,放在一個數組裏
console.log($('li:lt(1)')); //找到索引小於1的li,放在一個數組裏
console.log($('input[name=a]')); //獲取名字爲a的input
console.log($('input[name!=a]')); //獲取名字不爲a的input
console.log($("input[name^=ab]")); //獲取名字開頭爲ab的input
console.log($("input[name$=ab]")); //獲取名字結尾爲ab的input
console.log($('ul>li')); //獲取ul下的li
console.log($('ul+div')); //獲取緊接着ul的下一個兄弟元素,而且下一個兄弟元素必須是div標籤
console.log($('ul~input')); //獲取ul之後的所有input
</script>
</body>
2. jquery的常用方法
<body>
<div class="a" trueImg="1.jpg">
中國
</div>
<input type="text">
<script src="../../jquery-1.11.3.js"></script>
<script>
console.log($('.a').attr('trueImg')); //如果只有一個參數,獲取行間屬性
console.log($('.a').attr('b', 100)); //如果是兩個參數,就是設置行間屬性
console.log($('input').prop('checked')); //如果一個參數就是是否選中,選中爲true,沒選中爲false;兩個參數是設置是否選中
console.log($('.a').addClass('s')); //新增class類名
console.log($('.a').removeClass('a')); //刪除class類名
console.log($('.a').html()); //獲取標籤的內容,html可以識別標籤
console.log($('.a').text()); //獲取標籤的內容,text不可以識別標籤
console.log($('input').val('請輸入查詢密碼')); //設置文本框內容
console.log($('input').val()); //獲取文本框內容
</script>
</body>
3. jquery的CSS
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width:100px;
height:100px;
background: red;
padding:10px;
border:10px solid blue;
margin:1000px auto;
position: relative;
}
.box div{
position: absolute;
left:30px;
}
</style>
</head>
<body>
<div class="box">
<div>134</div>
</div>
<script src="../../jquery-1.11.3.js"></script>
<script>
console.log($('.box').css('winth')); //獲取.box的width值
console.log($('.box').css('width','200px')); //設置.box的width值爲200px
console.log($('.box').offset()); //獲取.box的偏移量
console.log($('.box').offset().left); //獲取.box的左偏移量
console.log($('.box div').position().left); //獲取.box下的div的定位屬性的左位移
console.log($('.box').innerWidth()); //獲取.box的clientWidth值
console.log($('.box').outerWidth()); //獲取.box的offsetWidth值
</script>
</body>
4. jquery的文檔處理
<body>
<div class="box">
<div></div>
</div>
<span>123</span>
<span>123</span>
<span>123</span>
<script src="../../jquery-1.11.3.js"></script>
<script>
console.log($('.box').append("<span>How are you?</span>")); //給.box新增一個span標籤
let a = document.createElement('a'); //創建一個a標籤
console.log($(a).addClass('cv')); //給a標籤加class名cv
console.log($('.box').append(a)); //將a標籤加到.box裏的後面
console.log($('span').appendTo('.box')); //將a標籤加到.box裏的後面
console.log($('.box').prepend($('span'))); //將span標籤置入到.box裏的前面
console.log($('span').prependTo('.box')); //將span標籤置入到.box裏的前面
console.log($('.box').after('<b>123</b>')); //將'<b>123</b>'添加到.box後面
console.log($('.box').before('<b>123</b>')); //將'<b>123</b>'添加到.box前面
console.log($('.box').empty()); //清空.box的dom元素
console.log($('span').remove()); //刪除所有匹配到的元素
</script>
5. jquery的篩選
- $(‘選擇器’).hasClass(‘a’) :判斷是否有某個類名,有就返回true沒有就返回false
- $(‘選擇器’).filter(‘條件,條件’) :篩選,按條件匹配,條件可以有多個
- $('選擇器**‘).has(’條件’****) :擁有對應的後代元素的選擇器**
- $("選擇器").find("li") :匹配後代元素
<body>
<ul class="list" style="position: absolute;">
<li class="a">1</li>
<li>2</li>
<li class="b">
<span></span>
</li>
<li>4</li>
</ul>
<p>Hello</p>
<p>Hello Again</p>
<p class="selected">And Again</p>
<script src="../../jquery-1.11.3.js"></script>
<script>
console.log($('.list li').eq(2).hasClass('a')); //false 判斷是否有某個類名,有返回true,沒有就返回false
console.log($('p').filter('.selected,:first')); //匹配出p標籤的有class名爲.selected和第一個
console.log($('li').has('span')); //有span標籤爲後代的li標籤
console.log($(".list").find("li")); //獲取.list下的全部li
console.log($('.a').next()); //下一個弟弟元素節點節點
console.log($('.a').nextAll()); //全部弟弟元素節點節點
console.log( $("span").offsetParent()) //用於定位的父元素節點
console.log( $("span").parent()) //父元素節點
console.log( $("span").parents()) //全部的父元素節點
console.log( $(".b").prev()); //上一個哥哥元素節點
console.log( $(".b").prevAll()); //全部的哥哥元素節點
console.log( $(".b").siblings()); //全部的兄弟元素節點
</script>
</body>
6. jquery的事件
- 在JQ中所有的事件都是通過addEventListener綁定的,所以當使用事件的時候如果不解除前一次綁定,那麼容易出現事件重複執行。
- 解決:off().click() 解除上一次的事件
- ready
- 相同點 :當DOM元素準備就緒會觸發一個函數;DOM結構,圖片,音視頻解析完成以後,纔會觸發的回調函數
- 不同點 :ready在同一個頁面中,可以有多個回調函數,並且按照順序依次執行
- click :事件點擊
<body>
<div class="box">1</div>
<div class="box">2</div>
<script src="../../jquery-1.11.3.js"></script>
<script>
console.log($(document).ready(function(){
console.log(1)
}));
//頁面加載完成事件
$(".box").click(function(){
console.log(this);
})
//點擊事件
function fn(){}
$(".box").on("click",fn)
//on增加事件
$(".box").off("click")
//off刪除事件
</script>
</body>
7. jquery的動畫
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box{
width:100px;
height:100px;
background: red;
}
</style>
</head>
<body>
<div class="box"></div>
<button id="btn">點擊</button>
<script src="../../jquery-1.11.3.js"></script>
<script>
$(".box").hide(); //隱藏
$(".box").show(); //顯示
$(".box").toggle();//如果隱藏就顯示,如果顯示就隱藏
$(".box").slideDown(); //從上面拉下來(顯示)
$(".box").slideUp(); //從上面收上去(隱藏)
$(".box").slideToggle(); //如果隱藏就顯示,如果顯示就隱藏
$(".box").fadeIn(); //通過改透明的讓盒子顯示
$(".box").fadeOut(); //通過改透明的讓盒子隱藏
$(".box").fadeToggle(1000);// 通過不斷改變透明度,讓盒子顯示隱藏;
$(".box").animate({
width:300,
height:200
},function(){
// 當動畫運動完成之後,執行該函數
//console.log(100);
$(".box").css("background","blue")
})
//animate 自定義動畫
</script>
</body>
8.清除某個事件再添加某個事件
$aa.off('click).click(function(){})
先清除某個事件再添加某個事件
用jq做選項卡
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 500px;
margin: 100px auto;
}
ul {
list-style: none;
display: flex;
position: relative;
top: 1px
}
li {
width: 150px;
margin-right: 10px;
height: 40px;
line-height: 40px;
font-size: 30px;
text-align: center;
border: 1px solid orangered;
}
.box div {
width: 500px;
border: 1px solid orangered;
height: 300px;
line-height: 300px;
text-align: center;
font-size: 50px;
display: none;
}
ul li.active {
border-bottom: 1px solid white;
}
.box div.active {
display: block;
}
</style>
<body>
<div id="box" class="box">
<ul id="navBox" class="navBox">
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
<div class="active">一</div>
<div>二</div>
<div>三</div>
</div>
<script src="../../js/jquery-1.11.3.js"></script>
<script>
let $navList = $('.box li');
let $tabList = $('.box div');
// // $navList.each(function(index, item){
// // console.log(index, item)
// // $(item).click(function(){
// // console.log(111)
// // })
// // })
// // 他會自動給每一個li加上點擊事件,內部就給你循環了
$navList.click(function () {
// // index()代表了當前點擊元素的位置的索引
// // eq()通過索引找到對應的元素
// let index = $(this).index(); // 獲取當前元素對應的索引
// $(this).addClass('active').siblings().removeClass('active');
// $tabList.eq(index).addClass('active').siblings().removeClass('active');
$(this).addClass('active').siblings().removeClass('active').parent().nextAll().eq($(this).index())
.addClass('active').siblings().removeClass('active')
})
</script>
</body>
JQ源碼簡單理解
<script>
(function (global, factory) {
// global就是 window
// factory是 function (window, noGlobal) {}
if (typeof module === "object" && typeof module.exports === "object") {
// ...
// 支持CommonJs模塊規範的執行這裏(例如node.js)
} else {
// 代碼能走到這裏說明是瀏覽器或者webView環境
// 當外層自執行代碼執行的時候,factory執行,function (window, noGlobal) {}
// window
// 也就是說function的裏第一個形參被賦值的實參就是window
factory(global);
}
// typeof windiw => 'object'
}(typeof window !== "undefined" ? window : this, function (window, noGlobal) {
// 參數信息
// window --> window
// noGlobal --> undefined
// ....
var version = "1.11.3",
jQuery = function (selector, context) {
return new jQuery.fn.init(selector, context);
};
// jQqury還一個自定義類,他們把jQuery的原型重定向了,
// 而且還給jQ加了一個屬性,屬性值也是自己的原型 jQuery.fn === jQuery.prototype
jQuery.fn = jQuery.prototype = {
// 這裏面是jQ的公有屬性和方法
jquery: version,
// 我們自己重定向後的原型是沒有construstor,所以他給手動增加了一個constructor屬性指向自己的類
// 爲了保證原型的完整性
constructor: jQuery,
// 轉換爲數組的方法
// this:一般是當前類jQuery的實例
toArray: function () {
// this:一般是當前類jQuery的實例
return slice.call(this);
},
// 把jQ對象轉換爲原生js對象
get: function (num) {
return num != null ?
// Return just the one element from the set
(num < 0 ? this[num + this.length] : this[num]) :
// Return all the elements in a clean array
slice.call(this);
},
each: function (callback, args) {
// this就是當前實例,
// each是jQ類的一個私有屬性(把jQ當做對象來用)
// 一會去jQ裏查each方法
return jQuery.each(this, callback, args);
},
eq: function (i) {
var len = this.length,
j = +i + (i < 0 ? len : 0);
return this.pushStack(j >= 0 && j < len ? [this[j]] : []);
},
}
// 把jQuery賦值給window的$和jQuery,這樣你就在全局下都可以使用了
if (typeof noGlobal === "undefined") {
window.jQuery = window.$ = jQuery;
}
}));
$()
//jQ提供的方法放到了兩個位置
// 1、原型上jQuery.prototype={toArray:fn}
// $().toArray()
// 只有jQ的實例纔可以調用
// 2、對象上jQuery.ajax = ...
// $.ajax()
// 直接調取使用
// 檢測當前對象是數組還是類數組
// function isArraylike(obj) {
// if (type === "function" || jQuery.isWindow(obj)) {
// return false;
// }
// if (obj.nodeType === 1 && length) {
// return true;
// }
// return type === "array" || length === 0 ||
// typeof length === "number" && length > 0 && (length - 1) in obj;
// }
</script>
jquery核心源碼
<script>
(function (global, factory) {
factory(global); // factory 是實參的回調函數
}(typeof window !== "undefined" ? window : this, function (window, noGlobal) {
// 在這個作用域準備了數組和對象的常用方法;
var deletedIds = [];
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var jQuery = function (selector, context) {
// jQuery執行時,會返回一個init的實例;
return new jQuery.fn.init(selector, context);
};
jQuery.fn = jQuery.prototype = {
// 這是jquery原型上的方法;jQuery實例能用;
jquery: version,
constructor: jQuery,
toArray: function () {
return slice.call(this);
},
}
// 是往原型上擴展方法的;
jQuery.extend = jQuery.fn.extend = function () {}
// 擴展傳一個對象,那麼jquery的實例以後就可以調用新擴展的方法了;
jQuery.extend({
toArray: function () {
},
slice: function () {
}
})
// 返回的init實例,就是通過傳入選擇器,獲取到的對應的元素
init = jQuery.fn.init = function (selector, context) {
}
//
init.prototype = jQuery.fn; // 把jQuery的prototype給了init的原型
// 把jQuery這個方法給了全局下的$
window.jQuery = window.$ = jQuery;
}))();
$("#box") // jQuery 的實例,可以調用jquery原型上的方法;
// $.addClass// jQuery 的實例,可以調用jquery原型上的方法;
// console.log(module);
// $("#box").prev();
// $.ajax
// $("#box").ajax()
// jquery的私有屬性和jquery這個類原型的方法;
</script>