今天的帖子會給你們展示50個jquery代碼片段,這些代碼能夠給你的javascript項目提供幫助。其中的一些代碼段是從jQuery1.4.2纔開始支持的做法,另一些則是真正有用的函數或方法,他們能夠幫助你又快又好地把事情完成。這些都是我儘量記住的有着最佳性能的代碼段,因此如果你發現你任何可以做得更好的地方的話,歡迎把你的版本粘貼在評論中!我希望你在這一文章中能找到有幫助的東西。
1. 如何創建嵌套的過濾器:
5 |
.filter( ":not(:has(.selected))" )
|
2. 如何重用元素搜索
01 |
var allItems = $("div.item"); |
02 |
var keepList = $("div#container1 div.item"); |
03 |
//現在你可以繼續使用這些jQuery對象來工作了。例如, |
04 |
//基於複選框裁剪“keep list”,複選框的名稱 |
07 |
$(formToLookAt + " input:checked").each(function() { |
08 |
keepList = keepList.filter("." + $(this).attr("name"));
|
3. 任何使用has()來檢查某個元素是否包含某個類或是元素:
4 |
$( "input" ).has( ".email" ).addClass( "email_icon" );
|
4. 如何使用jQuery來切換樣式表
2 |
$( 'link[media=' screen ']' ).attr( 'href' , 'Alternative.css' );
|
5. 如何限制選擇範圍(基於優化目的):
6 |
var in_stock = $( '#shopping_cart_items input.is_in_stock' );
|
1 |
< ul id = "shopping_cart_items" >
|
2 |
< li >< input type = "radio" value = "Item-X" name = "item" class = "is_in_stock" /> Item X</ li >
|
3 |
< li >< input type = "radio" value = "Item-Y" name = "item" class = "3-5_days" /> Item Y</ li >
|
4 |
< li >< input type = "radio" value = "Item-Z" name = "item" class = "unknown" /> Item Z</ li >
|
6. 如何正確地使用ToggleClass:
4 |
a.hasClass( 'blueButton' ) ? a.removeClass( 'blueButton' ) : a.addClass( 'blueButton' );
|
6 |
a.toggleClass( 'blueButton' );
|
7. 如何設置IE特有的功能:
8. 如何使用jQuery來代替一個元素:
1 |
$( '#thatdiv' ).replaceWith( 'fnuh' );
|
9. 如何驗證某個元素是否爲空:
1 |
if ($( '#keks' ).html()) {
|
10. 如何從一個未排序的集合中找出某個元素的索引號
1 |
$( "ul > li" ).click( function () {
|
2 |
var index = $( this ).prevAll().length;
|
11. 如何把函數綁定到事件上:
1 |
$( '#foo' ).bind( 'click' , function () {
|
2 |
alert( 'User clicked on "foo."' );
|
12. 如何追加或是添加html到元素中:
1 |
$( '#lal' ).append( 'sometext' );
|
13. 在創建元素時,如何使用對象字面量(literal)來定義屬性
1 |
var e = $( "" , { href: "#" , class: "a-class another-class" , title: "..." });
|
14. 如何使用多個屬性來進行過濾
3 |
var elements = $( '#someid input[type=sometype][value=somevalue]' ).get();
|
15. 如何使用jQuery來預加載圖像:
1 |
jQuery.preloadImages = function () {
|
2 |
for ( var i = 0; i < arguments.length; i++) {
|
3 |
$( "<img />" ).attr( 'src' , arguments[i]);
|
7 |
$.preloadImages( 'image1.gif' , '/path/to/image2.png' , 'some/image3.jpg' );
|
16. 如何爲任何與選擇器相匹配的元素設置事件處理程序:
01 |
$( 'button.someClass' ).live( 'click' , someFunction);
|
06 |
$( "table" ).each( function (){
|
07 |
$( "td" , this ).live( "hover" , function (){
|
08 |
$( this ).toggleClass( "hover" );
|
12 |
$( "table" ).delegate( "td" , "hover" , function (){
|
13 |
$( this ).toggleClass( "hover" );
|
17. 如何找到一個已經被選中的option元素:
1 |
$( '#someElement' ).find( 'option:selected' );
|
18. 如何隱藏一個包含了某個值文本的元素:
1 |
$( "p.value:contains('thetextvalue')" ).hide();
|
19. 如果自動滾動到頁面中的某區域
1 |
jQuery.fn.autoscroll = function (selector) {
|
2 |
$( 'html,body' ).animate(
|
3 |
{scrollTop: $(selector).offset().top},
|
8 |
$( '.area_name' ).autoscroll();
|
20. 如何檢測各種瀏覽器:
1 |
檢測Safari ( if ( $.browser.safari)),
|
2 |
檢測IE6及之後版本 ( if ($.browser.msie && $.browser.version > 6 )),
|
3 |
檢測IE6及之前版本 ( if ($.browser.msie && $.browser.version <= 6 )),
|
4 |
檢測FireFox 2及之後版本 ( if ($.browser.mozilla && $.browser.version >= '1.8' ))
|
21. 如何替換串中的詞
2 |
el.html(el.html().replace(/word/ig, '' ));
|
22. 如何禁用右鍵單擊上下文菜單:
1 |
$(document).bind( 'contextmenu' , function (e){
|
23. 如何定義一個定製的選擇器
1 |
$.expr[ ':' ].mycustomselector = function (element, index, meta, stack){
|
9 |
$( '.someClasses:test' ).doSomething();
|
24. 如何檢查某個元素是否存在
1 |
if ($( '#someDiv' ).length) {
|
25. 如何使用jQuery來檢測右鍵和左鍵的鼠標單擊兩種情況:
1 |
$( "#someelement" ).live( 'click' , function (e) {
|
2 |
if ( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
|
3 |
alert( "Left Mouse Button Clicked" );
|
4 |
} else if (e.button == 2) {
|
5 |
alert( "Right Mouse Button Clicked" );
|
26. 如何顯示或是刪除input域中的默認值
05 |
$( ".swap" ).each( function (i){
|
06 |
wap_val[i] = $( this ).val();
|
07 |
$( this ).focusin( function (){
|
08 |
if ($( this ).val() == swap_val[i]) {
|
11 |
}).focusout( function (){
|
12 |
if ($.trim($( this ).val()) == "" ) {
|
13 |
$( this ).val(swap_val[i]);
|
1 |
< input type = "text" value = "Enter Username here.." class = "swap" />
|
27. 如何在一段時間之後自動隱藏或關閉元素(支持1.4版本):
2 |
setTimeout( function () {
|
3 |
$( '.mydiv' ).hide( 'blind' , {}, 500)
|
6 |
$( ".mydiv" ).delay(5000).hide( 'blind' , {}, 500);
|
28. 如何把已創建的元素動態地添加到DOM中:
2 |
newDiv.attr( 'id' , 'myNewDiv' ).appendTo( 'body' );
|
29. 如何限制“Text-Area”域中的字符的個數:
01 |
jQuery.fn.maxLength = function (max){
|
03 |
var type = this .tagName.toLowerCase();
|
04 |
var inputType = this .type? this .type.toLowerCase() : null ;
|
05 |
if (type == "input" && inputType == "text" || inputType == "password" ){
|
09 |
else if (type == "textarea" ){
|
10 |
this .onkeypress = function (e){
|
12 |
var keyCode = ob.keyCode;
|
13 |
var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this .selectionStart != this .selectionEnd;
|
14 |
return !( this .value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
|
16 |
this .onkeyup = function (){
|
17 |
if ( this .value.length > max){
|
18 |
this .value = this .value.substring(0,max);
|
25 |
$( '#mytextarea' ).maxLength(500);
|
30. 如何爲函數創建一個基本的測試
3 |
test( "some other test" , function () {
|
7 |
equals( true , false , "failing test" );
|
8 |
equals( true , true , "passing test" );
|
31. 如何在jQuery中克隆一個元素:
1 |
var cloned = $( '#somediv' ).clone();
|
32. 在jQuery中如何測試某個元素是否可見
1 |
if ($(element).is( ':visible' ) == 'true' ) {
|
33. 如何把一個元素放在屏幕的中心位置:
1 |
jQuery.fn.center = function () {
|
2 |
this .css( 'position' , 'absolute' );
|
3 |
this .css( 'top' , ( $(window).height() - this .height() ) / +$(window).scrollTop() + 'px' );
|
4 |
this .css( 'left' , ( $(window).width() - this .width() ) / 2+$(window).scrollLeft() + 'px' );
|
34. 如何把有着某個特定名稱的所有元素的值都放到一個數組中:
1 |
var arrInputValues = new Array();
|
2 |
$( "input[name='table[]']" ).each( function (){
|
3 |
arrInputValues.push($( this ).val());
|
35. 如何從元素中除去html
02 |
$.fn.stripHtml = function () {
|
03 |
var regexp = /<( "[^" ]* "|'[^']*'|[^'" >])*>/gi;
|
04 |
this .each( function () {
|
05 |
$( this ).html( $( this ).html().replace(regexp,”") );
|
36. 如何使用closest來取得父元素:
1 |
$( '#searchBox' ).closest( 'div' );
|
37. 如何使用Firebug和Firefox來記錄jQuery事件日誌:
3 |
$( '#someDiv' ).hide().log( 'div hidden' ).addClass( 'someClass' );
|
4 |
jQuery.log = jQuery.fn.log = function (msg) {
|
6 |
console.log( "%s: %o" , msg, this );
|
38. 如何強制在彈出窗口中打開鏈接:
1 |
jQuery( 'a.popup' ).live( 'click' , function (){
|
2 |
newwindow=window.open($( this ).attr( 'href' ), '' , 'height=200,width=150' );
|
39. 如何強制在新的選項卡中打開鏈接:
1 |
jQuery( 'a.newTab' ).live( 'click' , function (){
|
2 |
newwindow=window.open($( this ).href);
|
3 |
jQuery( this ).target = "_blank" ;
|
40. 在jQuery中如何使用.siblings()來選擇同輩元素
2 |
$( '#nav li' ).click( function (){
|
3 |
$( '#nav li' ).removeClass( 'active' );
|
4 |
$( this ).addClass( 'active' );
|
7 |
$( '#nav li' ).click( function (){
|
8 |
$( this ).addClass( 'active' ).siblings().removeClass( 'active' );
|
41. 如何切換頁面上的所有複選框:
3 |
$( 'a' ).click( function () {
|
4 |
$( "input[type=checkbox]" ).attr( "checked" ,!tog);
|
42. 如何基於一些輸入文本來過濾一個元素列表:
3 |
$( '.someClass' ).filter( function () {
|
4 |
return $( this ).attr( 'value' ) == $( 'input#someId' ).val();
|
43. 如何獲得鼠標墊光標位置x和y
1 |
$(document).ready( function () {
|
2 |
$(document).mousemove( function (e){
|
3 |
$(’ #XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);
|
44. 如何把整個的列表元素(List Element,LI)變成可點擊的
1 |
$( "ul li" ).click( function (){
|
2 |
window.location=$( this ).find( "a" ).attr( "href" );
|
2 |
< li >< a href = "#" >Link 1</ a ></ li >
|
3 |
< li >< a href = "#" >Link 2</ a ></ li >
|
4 |
< li >< a href = "#" >Link 3</ a ></ li >
|
5 |
< li >< a href = "#" >Link 4</ a ></ li >
|
45. 如何使用jQuery來解析XML(基本的例子):
1 |
function parseXml(xml) {
|
3 |
$(xml).find( "Tutorial" ).each( function () {
|
4 |
$( "#output" ).append($( this ).attr( "author" ) + "" );
|
46. 如何檢查圖像是否已經被完全加載進來
1 |
$( '#theImage' ).attr( 'src' , 'image.jpg' ).load( function () {
|
2 |
alert( 'This Image Has Been Loaded' );
|
47. 如何使用jQuery來爲事件指定命名空間:
2 |
$( 'input' ).bind( 'blur.validation' , function (e){
|
6 |
$( 'input' ).data( 'validation.isValid' , true );
|
48. 如何檢查cookie是否啓用
2 |
dt.setSeconds(dt.getSeconds() + 60); |
3 |
document.cookie = "cookietest=1; expires=" + dt.toGMTString();
|
4 |
var cookiesEnabled = document.cookie.indexOf( "cookietest=" ) != -1;
|
49. 如何讓cookie過期:
2 |
date.setTime(date.getTime() + (x * 60 * 1000)); |
3 |
$.cookie( 'example' , 'foo' , { expires: date });
|
50. 如何使用一個可點擊的鏈接來替換頁面中任何的URL
01 |
$.fn.replaceUrl = function () {
|
02 |
var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w #!:.?+=&%@!\-\/]))?)/gi;
|
03 |
this .each( function () {
|
05 |
$( this ).html().replace(regexp,'<A href= "$1" >$1</A>‘)
|
由我愛互聯網於2011年8月12日校驗修訂。
本文永久鏈接:http://www.woiweb.net/50-jquery-snippets-for-developers.html