以下jQuery方法有什么作用茵乱?如何使用囱晴?給出范例
.append()
- 寫法:
.append(content[,content])/.append(function(index,html))
- 解釋: insert content, specified by the parameter, to the end of each element in the set of matched elements
- 拓展:可以一次添加多個內(nèi)容十兢,內(nèi)容可以是DOM對象置逻、HTML string辖源、jQuery對象
- 拓展:如果參數(shù)是function,function可以返回DOM對象竭缝、HTML string、jQuery對象傻粘,參數(shù)是集合中的元素位置與原來的html值
幾個小例子
$('.inner').append('<p>Test</p>');
$('body').append($newdiv1,[ newdiv2,existingdiv1 ]);
$('p').append('<strong>Hello</strong>')
$('p').append($('strong'))
$('p').append(document.creaTextNode('Hello'))
.prepend()
- 寫法:
.prepend(content[, content]) / .prepend(function(index,html))
- 解釋:向?qū)ο箢^部追加內(nèi)容每窖,用法和append類似,內(nèi)容添加到最開始
- 解釋:Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
幾個例子
$('.inner').prepend('<p>Test</p>')// 向class值為inner元素的頭部(內(nèi)部)添加內(nèi)容'<p>Test</p>'
.before()
- 寫法:
.before([content][,content]) / .before(function)
- 解釋:在對象前面(不是頭部抹腿,而是外面岛请,和對象并列同級)插入內(nèi)容旭寿,參數(shù)和append類似
- 解釋:Insert content, specified by the parameter, before each element in the set of matched elements.
幾個例子
$('.inner').before('<p>Test</p>')
$('.container').before($('h2'))
$('p').first().before( newdiv1, [ newdiv2, existingdiv1])
$('p').before('<b>Hello</b>')
$('p').before(document.createTextNode('Hello'))
.after()
- 寫法:
.after([content][,content]) / .after(function(index))
- 解釋:和before相反警绩,在對象后面(不是尾部,而是外面盅称,和對象并列同級)插入內(nèi)容肩祥,參數(shù)和append類似
- 解釋:Insert content,specified by the parameter, after each element in the set of matched elements.
幾個例子
$('.inner').after('<p>Test</p>') //在class值為inner的元素后面添加兄弟元素'<p>Test</p>'
$('p').after( document.createTextNode('Hello'))//
.remove()
- 寫法:
.remove([selector])
- 解釋:刪除被選中的元素(及其子元素)缩膝,同樣也可以添加一個可選的選擇器參數(shù)來過濾匹配的元素
舉例
$('#div1').remove() //刪除id為div1的元素及其子元素
$('div').remove('.test')//刪除帶有class值為test的div元素
.empty()
- 寫法即為
.empty()
- 作用:清空被選擇元素內(nèi)所有子元素
- 解釋:Remove all child nodes of the set of matched elements from the DOM
- 舉例:
$('body').empty()
//清空body內(nèi)的所有子元素
.html()
- 寫法:
.html([string])
- 解釋:這是一個讀寫兩用的方法混狠,用于獲取、修改元素的innerHTML
- 解釋:當沒有傳遞參數(shù)時疾层,返回元素的innerHTML
- 解釋:當傳遞了一個string參數(shù)的時候将饺,修改元素的innerHTML為參數(shù)值
幾個例子
$('div').html() //獲取所選元素的innerHTML
$('div').html('123')//將所選元素的innerHTML設(shè)置為‘123’
- 補充:后續(xù)這種讀寫兩用的方法很多,原理都類似
- 補充:如果結(jié)果是多個進行賦值操作的時候會給每個結(jié)果都賦值
- 補充:如果結(jié)果多個痛黎,獲取值的時候予弧,返回結(jié)果集中的第一個對象的相應(yīng)值
.text()
- 和html方法類似,操作的是DOM的innerText的值
$node.text()
和$node.html()
有什么區(qū)別湖饱?
-
$node.html()
:獲取集合中第一個匹配元素的html內(nèi)容掖蛤,或設(shè)置每一個元素的html內(nèi)容。
-
$node.text()
:獲取匹配元素集合中每個元素的合并文本井厌,包括它們的后代蚓庭,或設(shè)置匹配元素集合中每個元素的文本內(nèi)容為指定的文本內(nèi)容。
介紹以下 jQuery 函數(shù)的用法仅仆,給出范例
.val()
- 解釋:這是一個讀寫雙用的方法器赞,用來處理input的value,當方法沒有參數(shù)的時候返回input的value值墓拜,當傳遞了一個參數(shù)的時候硼端,方法修改input的value值為參數(shù)值
舉例
$('input').val()
$('input').val('newValue');
.attr()
- 寫法:
.sttr(sttributeName)
- 作用:獲取元素特定屬性的值
- Get the value of an attribute for the first element in the set of matched elements
var title = $( "em" ).attr( "title" );
- 擴展寫法:
.attr(attributeName,value) / .attr(attributesJson) / .attr( attributeName, function(index, attr) ).
- 作用:為元素屬性賦值 Set one or more attributes for the set of matched elements.
$( "#greatphoto" ).attr( "alt", "Beijing Brush Seller" );
$( "#greatphoto" ).attr({
alt: "Beijing Brush Seller",
title: "photo by Kelly Clark"
});
$( "#greatphoto" ).attr( "title", function( i, val ) {
return val + " - photo by Kelly Clark";
});
.removeAttr()
- 為匹配的元素集合中的每個元素中移除一個屬性(attribute)
-
.removeAttr()
方法使用原生的 JavaScript removeAttribute() 函數(shù),但是它的優(yōu)點是可以直接在一個 jQuery 對象上調(diào)用該方法当宴,并且它解決了跨瀏覽器的屬性名不同的問題每强。
$('div').removeAttr('id');
.prop()/.removeProp()
- 這兩個方法是用來操作元素的property的笨奠,property和attibute是非常相似的概念,用法類似
.css()
- 寫法:
.css(propertyName,value) / .css( propertyName, function(index, value) ) / .css( propertiesJson )
- 作用:Set one or more CSS properties for the set of matched elements.
設(shè)置元素style特定property的值
$( "div.example" ).css( "width", function( index ) {
return index * 50;
});
$( this ).css( "width", "+=200" );
$( this ).css( "background-color", "yellow" );
$( this ).css({
"background-color": "yellow",
"font-weight": "bolder"
});
.addClass()
- 寫法:
.addClass(className) / .addClass(function(index,currentClass))
- 作用:為元素添加class歌亲,不是覆蓋原有class,是追加,也不會檢查重復(fù)
adds the specified class(es) to each of the set of matched elements.
$( "p" ).addClass( "myClass yourClass" );
$( "ul li" ).addClass(function( index ) {
return "item-" + index;
});
.removeClass()
- 寫法:
removeClass([className]) / ,removeClass(function(index,class))
- 作用:移除元素單個/多個/所有class`
remove a single class, multiple classes, or all classes from each element in the set of matched elements.
$( "p" ).removeClass( "myClass yourClass" );
$( "li:last" ).removeClass(function() {
return $( this ).prev().attr( "class" );
});
.hasClass()
- 檢查元素是否包含某個class救恨,返回true/false,Determine whether any of the matched elements are assigned the given class.
- 舉例:
$( "#mydiv" ).hasClass( "foo" )
.toggleClass()
- toggle是切換的意思释树,方法用于切換肠槽,switch是個bool類型值,這個看例子就明白
<div class="tumble">Some text.</div>`
第一次執(zhí)行
$( "div.tumble" ).toggleClass( "bounce" )
<div class="tumble bounce">Some text.</div>
第二次執(zhí)行
$( "div.tumble" ).toggleClass( "bounce" )
<div class="tumble">Some text.</div>
jQuery 對象和原生 Dom 對象有什么區(qū)別奢啥?如何相互轉(zhuǎn)換秸仙?
- jQuery對象是一個類數(shù)組對象,對象原型封裝了許多jQuery自定義的方法桩盲。在jQuery對象中無法使用DOM對象的任何方法
- DOM 對象===>jQuery,加
$
符號
var dom = document.getElementById("id");//DOM對象
var $dom = $(dom);//jq對象
- jQuery==>DOM對象,后面加[0]即可完成轉(zhuǎn)換
var $dom = $("#id");//jq對象
var dom = $dom[0];//DOM對象
介紹以下 jQuery 方法的用法寂纪,給出范例
.each()
- 寫法:
.each(function(index,Element))
- 作用:遍歷一個jquery對象,為每個匹配元素執(zhí)行一個函數(shù)
S('li').each(function(index){console.log(index + ":" + $(this).text())})
- 寫法:
jQuery.each(collection,callback(indexInArray, valueOfElement))
- 作用:一個通用的迭代函數(shù)赌结,它可以用來無縫迭代對象和數(shù)組捞蛋。數(shù)組和類似數(shù)組的對象通過一個長度屬性(如一個函數(shù)的參數(shù)對象)來迭代數(shù)字索引,從0到length-1.其他對象通過其屬性名進行迭代
var obj = { "flammable":"inflammable", "duh":"no duh"};
$.each(obj,function(key,value){alert(key + ":" +value);})
$.extend()
- 寫法:jQuery.extend([deep,] target [, object1 ] [, objectN ] )
- 當我們提供兩個或多個對象給$.extend()柬姚,對象的所有屬性都添加到目標對象(target參數(shù))拟杉。
- 如果只有一個參數(shù)提供給$.extend(),這意味著目標參數(shù)被省略量承。在這種情況下搬设,jQuery對象本身被默認為目標對象。這樣撕捍,我們可以在jQuery的命名空間下添加新的功能拿穴。這對于插件開發(fā)者希望向 jQuery 中添加新函數(shù)時是很有用的
- 目標對象(第一個參數(shù))將被修改,并且將通過.extend({}, object1, object2);`
- 在默認情況下阀蒂,通過
$.extend()
合并操作不是遞歸的;
- 如果第一個對象的屬性本身是一個對象或數(shù)組该窗,那么它將完全用第二個對象相同的key重寫一個屬性。這些值不會被合并蚤霞。如果將 true作為該函數(shù)的第一個參數(shù)酗失,那么會在對象上進行遞歸的合并。
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
}; // Merge object2 into object1
$.extend( object1, object2 );
.clone()
- 寫法.clone([withDataAndEvents])
-
.clone()
方法深度復(fù)制所有匹配的元素集合昧绣,包括所有匹配元素规肴、匹配元素的下級元素、文字節(jié)點
- 通常我們將頁面上一個元素插入到DOM里另一個地方,它會被從老地方移走拖刃,類似剪切的效果
$('.hello').appendTo('.goodbye');
<div class="container">
<div class="goodbye">
Goodbye
<div class="hello">Hello</div>
</div>
</div>
- 但是我們?nèi)绻枰氖菑?fù)制而不是剪切删壮,我們可以像下面這樣寫代碼:
$('.hello').clone().appendTo('.goodbye');
.index()
- 寫法
.index() / .index(selector)/ .index(element)
- 作用:從給定集合中查找特定元素index
Search for a given element from among the matched elements.
- 沒參數(shù)返回第一個元素index
- 如果參數(shù)是DOM對象或者jQuery對象,則返回參數(shù)在集合中的index
- 如果參數(shù)是選擇器兑牡,返回第一個匹配元素index央碟,沒有找到返回-1
舉個例子
var listItem = $( "#bar" );
alert( "Index: " + $( "li" ).index( listItem ) );
.ready()
- 當DOM準備就緒時,指定一個函數(shù)來執(zhí)行均函。
- 雖然JavaScript提供了load事件亿虽,當頁面呈現(xiàn)時用來執(zhí)行這個事件,直到所有的東西苞也,如圖像已被完全接收前洛勉,此事件不會被觸發(fā)。
- 在大多數(shù)情況下如迟,只要DOM結(jié)構(gòu)已完全加載時收毫,腳本就可以運行。傳遞處理函數(shù)給.ready()方法氓涣,能保證DOM準備好后就執(zhí)行這個函數(shù)牛哺,因此陋气,這里是進行所有其它事件綁定及運行其它 jQuery 代碼的最佳地方劳吠。
- 如果執(zhí)行的代碼需要在元素被加載之后才能使用時,(例如巩趁,取得圖片的大小需要在圖片被加載完后才能知道)痒玩,就需要將這樣的代碼放到 load 事件中。
下面兩種語法全部是等價的:
$(document).ready(handler)
$(handler)
- 我們也經(jīng)常這樣使用
$(function(){ console.log('ready');});
window.onload
和$(document).ready
有什么區(qū)別议慰?document.onDOMContentLoaded
呢?
- 執(zhí)行時間
-
window.onload
必須等到頁面內(nèi)包括圖片的所有元素加載完畢后再去執(zhí)行蠢古。
-
$(document).ready()
時DOM結(jié)構(gòu)回執(zhí)完畢后就執(zhí)行,不必等到加載完畢别凹。
- 方法個數(shù)
-
window.onload
不同同時編寫多個草讶,如果有多個window.onload
方法,只會執(zhí)行一個
- $(document).ready()可以同時編寫多個炉菲,并且可以得到執(zhí)行
- 簡化寫法
- window.onload沒有簡化寫法
-
(function(){});
- document.onDOMContentLoaded在頁面中觸發(fā)[DOMContentLoaded]事件時觸發(fā)堕战。此時,文檔被加載和解析拍霜,并且DOM被完全構(gòu)造嘱丢,但鏈接的資源(例如圖像,樣式表和子幀)可能尚未被加載祠饺。
jQuery實現(xiàn)點擊icon后切換播放和暫停兩種狀態(tài)
<!DOCTYPE html>
<html lang='en'>
<head>
<link rel='stylesheet' >
<script src='http://cdn.bootcss.com/jquery/3.3.1/jquery.js'>
<meta charset="UTF-8">
<title>icon-change</title>
<style>
.fa{
color:red;
font-size: 40px;
margin: 100px;
}
</style>
</head>
<body>
<div class="fa fa-pause"></div>
<script>
$('.fa').on('click',function(){$('.fa').toggleClass('fa-play')})
$('.fa').on('click',function(){$('.fa').toggleClass('fa-pause')})
</script>
</body>
</html>