了解了這些才能開始發(fā)揮jQuery的威力
由于當(dāng)前jQuery如此的如雷貫耳,相信不用介紹什么是jQuery了,公司代碼中廣泛應(yīng)用了jQuery,但我在看一些小朋友的代碼時(shí)發(fā)現(xiàn)一個(gè)問(wèn)題,小朋友們使用的僅僅是jQuery的皮毛,只是使用id選擇器與attr方法,還有幾個(gè)動(dòng)畫,如果只是如此,相比于其帶來(lái)的開銷,其實(shí)還不如不使用,下面介紹幾個(gè)jQuery常用的方法,來(lái)讓jQuery的威力發(fā)揮出來(lái),否則只用有限的幾個(gè)方法,相對(duì)于運(yùn)行速度問(wèn)題,真不如不用jQuery。
jQuery如此之好用,和其在獲取對(duì)象時(shí)使用與CSS選擇器兼容的語(yǔ)法有很大關(guān)系,畢竟CSS選擇器大家都很熟悉(關(guān)于CSS選擇器可以看看十分鐘搞定CSS選擇器),但其強(qiáng)大在兼容了CSS3的選擇器,甚至多出了很多。
選擇器
有了CSS選擇器基礎(chǔ)后,看jQuery的選擇器就很簡(jiǎn)單了,不再詳細(xì)一一說(shuō)明
基本選擇器 | |
$(‘*') | 匹配頁(yè)面所有元素 |
$(‘#id') | id選擇器 |
$(‘.class') | 類選擇器 |
$(‘element') | 標(biāo)簽選擇器 |
組合/層次選擇器 | |
$(‘E,F') | 多元素選擇器,用”,分隔,同時(shí)匹配元素E或元素F |
$(‘E F') | 后代選擇器,用空格分隔,匹配E元素所有的后代(不只是子元素、子元素向下遞歸)元素F |
$(E>F) | 子元素選擇器,用”>”分隔,匹配E元素的所有直接子元素 |
$(‘E+F') | 直接相鄰選擇器,匹配E元素之后的相鄰的同級(jí)元素F |
$(‘E~F') | 普通相鄰選擇器(弟弟選擇器),匹配E元素之后的同級(jí)元素F(無(wú)論直接相鄰與否) |
$(‘.class1.class2') | 匹配類名中既包含class1又包含class2的元素 |
基本過(guò)濾選擇器 | |
$("E:first") | 所有E中的第一個(gè) |
$("E:last") | 所有E中的最后一個(gè) |
$("E:not(selector)") | 按照selector過(guò)濾E |
$("E:even") | 所有E中index是偶數(shù) |
$("E:odd") | 所有E中index是奇數(shù) |
$("E:eq(n)") | 所有E中index為n的元素 |
$("E:gt(n)") | 所有E中index大于n的元素 |
$("E:ll(n)") | 所有E中index小于n的元素 |
$(":header") | 選擇h1~h7 元素 |
$("div:animated") | 選擇正在執(zhí)行動(dòng)畫效果的元素 |
內(nèi)容過(guò)濾器 | |
$(‘E:contains(value)') | 內(nèi)容中包含value值的元素 |
$(‘E:empty') | 內(nèi)容為空的元素 |
$(‘E:has(F)') | 子元素中有F的元素,$(‘div:has(a)'):包含a標(biāo)簽的div |
$(‘E: parent') | 父元素是E的元素,$(‘td: parent'):父元素是td的元素 |
可視化選擇器 | |
$(‘E:hidden') | 所有被隱藏的E |
$(‘E:visible') | 所有可見(jiàn)的E |
屬性過(guò)濾選擇器 | |
$(‘E[attr]') | 含有屬性attr的E |
$(‘E[attr=value]') | 屬性attr=value的E |
$(‘E[attr !=value]') | 屬性attr!=value的E |
$(‘E[attr ^=value]') | 屬性attr以value開頭的E |
$(‘E[attr $=value]') | 屬性attr以value結(jié)尾的E |
$(‘E[attr *=value]') | 屬性attr包含value的E |
$(‘E[attr][attr *=value]') | 可以連用 |
子元素過(guò)濾器 | |
$(‘E:nth-child(n)') | E的第n個(gè)子節(jié)點(diǎn) |
$(‘E:nth-child(3n+1)') | E的index符合3n+1表達(dá)式的子節(jié)點(diǎn) |
$(‘E:nth-child(even)') | E的index為偶數(shù)的子節(jié)點(diǎn) |
$(‘E:nth-child(odd)') | E的index為奇數(shù)的子節(jié)點(diǎn) |
$(‘E:first-clild') | 所有E的第一個(gè)子節(jié)點(diǎn) |
$(‘E:last-clild') | 所有E的最后一個(gè)子節(jié)點(diǎn) |
$(‘E:only-clild') | 只有唯一子節(jié)點(diǎn)的E的子節(jié)點(diǎn) |
表單元素選擇器 | |
$(‘E:type') | 特定類型的input |
$(‘:checked') | 被選中的checkbox或radio |
$(‘option: selected') | 被選中的option |
篩選方法
.find(selector) 查找集合每個(gè)元素的子節(jié)點(diǎn)
Get the descendants(子節(jié)點(diǎn)) of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
.filter(selector) 過(guò)濾當(dāng)前集合內(nèi)元素
Reduce(減少) the set of matched elements to those that match the selector or pass the function's test.
基本方法
.ready(handler) 文檔加載完成后執(zhí)行的方法,區(qū)別于window.onload
Specify a function to execute when the DOM is fully loaded.
$(document).ready(function() {
// Handler for .ready() called.
});
.each(function(index,element)) 遍歷集合內(nèi)每個(gè)元素
Iterate over a jQuery object, executing a function for each matched element.
$("li" ).each(function( index ) {
console.log( index + ": " + $(this).text() );
});
jQuery.extend( target [, object1 ] [, objectN ] ) 合并對(duì)象
Merge the contents of two or more objects together into the first object.
獲取元素
.eq(index) 按index獲取jQuery對(duì)象集合中的某個(gè)特定jQuery對(duì)象
Reduce the set of matched elements to the one at the specified index.
.eq(-index) 按逆序index獲取jQuery對(duì)象集合中的某個(gè)特定jQuery對(duì)象
An integer indicating the position of the element, counting backwards from the last element in the set.
.get(index) 獲取jQuery集合對(duì)象中某個(gè)特定index的DOM對(duì)象(將jQuery對(duì)象自動(dòng)轉(zhuǎn)換為DOM對(duì)象)
Retrieve one of the DOM elements matched by the jQuery object.
.get() 將jQuery集合對(duì)象轉(zhuǎn)換為DOM集合對(duì)象并返回
Retrieve the DOM elements matched by the jQuery object.
.index() / .index(selector)/ .index(element) 從給定集合中查找特定元素index
Search for a given element from among the matched elements.
1. 沒(méi)參數(shù)返回第一個(gè)元素index
2.如果參數(shù)是DOM對(duì)象或者jQuery對(duì)象,則返回參數(shù)在集合中的index
3.如果參數(shù)是選擇器,返回第一個(gè)匹配元素index,沒(méi)有找到返回-1
var listItem = $( "#bar" );
alert( "Index: " + $( "li" ).index( listItem ) );
.clone([withDataAndEvents][,deepWithDataAndEvents]) 創(chuàng)建jQuery集合的一份deep copy(子元素也會(huì)被復(fù)制),默認(rèn)不copy對(duì)象的shuju和綁定事件
Create a deep copy of the set of matched elements.
.parent([selector]) 獲取jQuery對(duì)象符合selector的父元素
Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
.parents([selector]) 獲取jQuery對(duì)象符合選擇器的祖先元素
Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
插入元素
.append(content[,content]) / .append(function(index,html)) 向?qū)ο笪膊孔芳觾?nèi)容
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
1. 可以一次添加多個(gè)內(nèi)容,內(nèi)容可以是DOM對(duì)象、HTML string、 jQuery對(duì)象
2. 如果參數(shù)是function,function可以返回DOM對(duì)象、HTML string、 jQuery對(duì)象,參數(shù)是集合中的元素位置與原來(lái)的html值
$( ".inner" ).append( "<p>Test</p>" );
$( "body" ).append( $newdiv1, [ newdiv2, existingdiv1 ] );
$( "p" ).append( "<strong>Hello</strong>" );
$( "p" ).append( $( "strong" ) );
$( "p" ).append( document.createTextNode( "Hello" ) );
.appendTo(target) 把對(duì)象插入到目標(biāo)元素尾部,目標(biāo)元素可以是selector, DOM對(duì)象, HTML string, 元素集合,jQuery對(duì)象;
Insert every element in the set of matched elements to the end of the target.
$( "h2" ).appendTo( $( ".container" ) );
$( "<p>Test</p>" ).appendTo( ".inner" );
.prepend(content[,content]) / .prepend(function(index,html)) 向?qū)ο箢^部追加內(nèi)容,用法和append類似
Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
.prependTo(target) 把對(duì)象插入到目標(biāo)元素頭部,用法和prepend類似
Insert every element in the set of matched elements to the beginning of the target.
.before([content][,content]) / .before(function) 在對(duì)象前面(不是頭部,而是外面,和對(duì)象并列同級(jí))插入內(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" ) );
.insertBefore(target) 把對(duì)象插入到target之前(同樣不是頭部,是同級(jí))
Insert every element in the set of matched elements before the target.
.after([content][,content]) / .after(function(index)) 和before相反,在對(duì)象后面(不是尾部,而是外面,和對(duì)象并列同級(jí))插入內(nèi)容,參數(shù)和append類似
Insert content, specified by the parameter, after each element in the set of matched elements.
$( ".inner" ).after( "<p>Test</p>" );
$( "p" ).after( document.createTextNode( "Hello" ) );
.insertAfter(target) 和insertBefore相反,把對(duì)象插入到target之后(同樣不是尾部,是同級(jí))
Insert every element in the set of matched elements after the target.
$( "<p>Test</p>" ).insertAfter( ".inner" );
$( "p" ).insertAfter( "#foo" );
包裹元素
.wrap(wrappingElement) / .wrap(function(index)) 為每個(gè)對(duì)象包裹一層HTML結(jié)構(gòu),可以是selector, element, HTML string, jQuery object
Wrap an HTML structure around each element in the set of matched elements.
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>$( ".inner" ).wrap( "<div class='new'></div>" );
<div class="container">
<div class="new">
<div class="inner">Hello</div>
</div>
<div class="new">
<div class="inner">Goodbye</div>
</div>
</div>
.wrapAll(wrappingElement) 把所有匹配對(duì)象包裹在同一個(gè)HTML結(jié)構(gòu)中
Wrap an HTML structure around all elements in the set of matched elements.
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>$( ".inner" ).wrapAll( "<div class='new' />");<div class="container">
<div class="new">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
</div>
.wrapInner(wrappingElement) / .wrapInner(function(index)) 包裹匹配元素內(nèi)容,這個(gè)不好說(shuō),一看例子就懂
Wrap an HTML structure around the content of each element in the set of matched elements.
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>$( ".inner" ).wrapInner( "<div class='new'></div>");
<div class="container">
<div class="inner">
<div class="new">Hello</div>
</div>
<div class="inner">
<div class="new">Goodbye</div>
</div>
</div>
.unwap() 把DOM元素的parent移除
Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
屬性方法
.val() 獲取元素的value值
Get the current value of the first element in the set of matched elements.
$( "input:checkbox:checked" ).val();
.val(value) /.val(function(index,value)) 為元素設(shè)置值,index和value同樣是指在為集合中每個(gè)元素設(shè)置的時(shí)候該元素的index和原value值
Set the value of each element in the set of matched elements.
$( "input" ).val( ‘hello' );
$( "input" ).on( "blur", function() {
$( this ).val(function( i, val ) {
return val.toUpperCase();
});
});
.attr(attributeName) 獲取元素特定屬性的值
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";
});
.prop( propertyName ) 獲取元素某特性值
Get the value of a property for the first element in the set of matched elements.
$( elem ).prop( "checked" )
.prop(propertyName,value) / .prop(propertiesJson) / .prop(propertyName,function(index,oldPropertyValue)) 為元素特性賦值
Set one or more properties for the set of matched elements.
$( "input" ).prop( "checked", true );
$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
return !val;
});
$( "input[type='checkbox']" ).prop({
disabled: true
});
關(guān)于attribute 和 property區(qū)別可以看看 jQuery的attr與prop
.data(key,value) / .value(json) 為HTML DOM元素添加數(shù)據(jù),HTML5元素 已有data-*屬性
Store arbitrary data associated with the matched elements.The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.
$( "body" ).data( "foo", 52 );
$( "body" ).data( "bar", { myType: "test", count: 40 } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );
.data(key) / .data() 獲取獲取data設(shè)置的數(shù)據(jù)或者HTML5 data-*屬性中的數(shù)據(jù)
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
alert( $( "body" ).data( "foo" ) );
alert( $( "body" ).data() );
alert( $( "body" ).data( "foo" ) ); // undefined
$( "body" ).data( "bar", "foobar" );
alert( $( "body" ).data( "bar" ) ); // foobar
CSS方法
.hasClass(calssName) 檢查元素是否包含某個(gè)class,返回true/false
Determine whether any of the matched elements are assigned the given class.
.addClass(className) / .addClass(function(index,currentClass)) 為元素添加class,不是覆蓋原class,是追加,也不會(huì)檢查重復(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([className]) / ,removeClass(function(index,class)) 移除元素單個(gè)/多個(gè)/所有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" );
});
.toggleClass(className) /.toggleClass(className,switch) / .toggleClass([switch]) / .toggleClass( function(index, class, switch) [, switch ] ) toggle是切換的意思,方法用于切換,switch是個(gè)bool類型值,這個(gè)看例子就明白
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
<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>
$( "#foo" ).toggleClass( className, addOrRemove );
// 兩種寫法意思一樣
if ( addOrRemove ) {
$( "#foo" ).addClass( className );
} else {
$( "#foo" ).removeClass( className );
}
$( "div.foo" ).toggleClass(function() {
if ( $( this ).parent().is( ".bar" ) ) {
return "happy";
} else {
return "sad";
}
});
.css(propertyName) / .css(propertyNames) 獲取元素style特定property的值
Get the value of style properties for the first element in the set of matched elements.
var color = $( this ).css( "background-color" );
var styleProps = $( this ).css([
"width", "height", "color", "background-color"
]);
.css(propertyName,value) / .css( propertyName, function(index, value) ) / .css( propertiesJson ) 設(shè)置元素style特定property的值
Set one or more CSS properties for the set of matched elements.
$( "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"
});
事件方法
.bind( eventType [, eventData ], handler(eventObject) ) 綁定事件處理程序,這個(gè)經(jīng)常用,不多解釋
Attach a handler to an event for the elements.
$( "#foo" ).bind( "click", function() {
alert( "User clicked on 'foo.'" );
});
.delegate( selector, eventType, handler(eventObject) ) 這個(gè)看官方解釋吧
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
$( "table" ).on( "click", "td", function() {//這樣把td的click事件處理程序綁在table上
$( this ).toggleClass( "chosen" );
});
.on( events [, selector ] [, data ], handler(eventObject) ) 1.7后推薦使用,取代bind、live、delegate
Attach an event handler function for one or more events to the selected elements.
$( "#dataTable tbody" ).on( "click", "tr", function() {
alert( $( this ).text() );
});
關(guān)于bind、live、delegate、on的區(qū)別可以看看 jQuery三種事件綁定方式.bind(),.live(),.delegate()
.trigger( eventType [, extraParameters ] ) JavaScript出發(fā)元素綁定事件
Execute all handlers and behaviors attached to the matched elements for the given event type.
$( "#foo" ).trigger( "click" );
.toggle( [duration ] [, complete ] ) / .toggle( options ) 隱藏或顯示元素
Display or hide the matched elements.
$( ".target" ).toggle();$( "#clickme" ).click(function() {
$( "#book" ).toggle( "slow", function() {
// Animation complete.
});
});
動(dòng)畫/Ajax
這兩部分內(nèi)容比較多,不是簡(jiǎn)單的一個(gè)function就可以的,這里只是列舉一下常用方法名,關(guān)于其使用可以看看 jQuery API animation ajax ,或者 jQuery的動(dòng)畫處理總結(jié),ASP.NET 使用Ajax動(dòng)畫
queue/dequeue/clearQueue
delay/stop
fadeIn/fadeOut/fadeTo/fadeToggle
slideUp/slideDown/slideToggle
show/hide
Ajax
$.ajax
$.load
$.get
最后
了解了上面這些內(nèi)容,使用jQuery進(jìn)行web開發(fā)的時(shí)候就可以體驗(yàn)到j(luò)Query的威力了。本文不是jQuery學(xué)習(xí)指南,僅僅是個(gè)常用方法介紹,如果大家想學(xué)習(xí)jQuery,最好的教材還是jQuery API,本文中示例與英文解釋全部來(lái)源于jQuery API。 另外文中介紹內(nèi)容遠(yuǎn)遠(yuǎn)不是jQuery全部,但是首先掌握了這些可以對(duì)jQuery有一個(gè)比較全面的認(rèn)識(shí),然后再學(xué)習(xí)其他內(nèi)容的時(shí)候就可以游刃有余了。
相關(guān)文章
jQuery之浮動(dòng)窗口實(shí)現(xiàn)代碼(兩種方法)
今天公司要求實(shí)現(xiàn)浮動(dòng)窗口效果,自己看了不少資料終于實(shí)現(xiàn)此效果。用jQ實(shí)現(xiàn)浮動(dòng)窗口功能,彈出窗口時(shí)背景變暗.2010-09-09jquery實(shí)現(xiàn)鼠標(biāo)懸浮彈出氣泡提示框
這篇文章主要為大家詳細(xì)介紹了jquery實(shí)現(xiàn)鼠標(biāo)懸浮彈出氣泡提示框,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12jquery實(shí)現(xiàn)下拉菜單的手風(fēng)琴效果
這篇文章主要為大家詳細(xì)介紹了jquery實(shí)現(xiàn)下拉菜單的手風(fēng)琴效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07為jquery的ajaxfileupload增加附加參數(shù)的方法
這篇文章主要介紹了為jquery的ajaxfileupload增加附加參數(shù)的方法,需要的朋友可以參考下2014-03-03jQuery插件jQuery-JSONP開發(fā)ajax調(diào)用使用注意事項(xiàng)
jQuery-JSONP是一個(gè)支持 JSONP 調(diào)用的 jQuery 插件,使用它是因?yàn)樗С殖鲥e(cuò)時(shí)的 ajax 回調(diào),而 jQuery 的 $.ajax 不支持,我們已經(jīng)在實(shí)際項(xiàng)目中使用,在開始使用時(shí)遇到了2個(gè)問(wèn)題,在這里記錄并分享一下。2013-11-11jquery(live)中File input的change方法只起一次作用的解決辦法
jquery中File input的change方法只起一次作用的解決辦法,需要的朋友可以參考下。2011-10-10jQuery實(shí)現(xiàn)簡(jiǎn)易的天天愛(ài)消除小游戲
貌似最近騰訊手機(jī)游戲天天愛(ài)消除挺火的,我也是粉絲之一,最近對(duì)javascript一直比較感興趣然后想用js仿造一個(gè),應(yīng)該不是太難,2015-10-10jQuery插件jquery.kxbdmarquee.js實(shí)現(xiàn)無(wú)縫滾動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了jQuery常用插件jquery.kxbdmarquee.js使用方法詳解,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02