This article shows you 50 jquery code snippets that can help your javascript projects. Some of the code snippets are practices that have only been supported since jQuery 1.4.2, and others are really useful functions or methods that can help you get things done quickly and well. These are the snippets of code that I try to remember for the best performance, so if you see anything you could do better, feel free to paste your version in the comments! I hope you found this article helpful.
1. How to create nested filters
2. How to reuse element search
1 2 3 4 | var allItems = $( "div.item" ); var keepList = $( "div#container1 div.item" );
<DIV> class names:
$(formToLookAt + " input:checked" ).each( function () { keepList = keepList.filter( "." + $(this).attr( "name" )); });
</DIV>
|
Copy after login
3. Anyone who uses has() to check whether an element contains a certain class or element
4. How to use jQuery to switch style sheets
1 2 | $(‘link[media=”screen”] ').attr(‘href' , ‘Alternative.css');
|
Copy after login
5. How to limit the selection range (based on optimization purposes)
1 2 3 |
var in_stock = $( '#shopping_cart_items input.is_in_stock' );
<ul id= "shopping_cart_items" > <li><input type= "radio" value= "Item-X" name= "item" class = "is_in_stock" />Item X</li> <li><input type= "radio" value= "Item-Y" name= "item" class = "3-5_days" />Item Y</li> <li><input type= "radio" value= "Item-Z" name= "item" class = "unknown" />Item Z</li> </ul>
|
Copy after login
6. How to use ToggleClass correctly
1 2 3 4 5 |
a.hasClass( 'blueButton' ) ? a.removeClass( 'blueButton' ) : a.addClass( 'blueButton' );
a.toggleClass(‘blueButton');
|
Copy after login
7. How to set up IE-specific functions
8. How to use jQuery to replace an element
1 | $(‘#thatdiv ').replaceWith(‘fnuh' );
|
Copy after login
9. How to verify whether an element is empty
1 2 3 4 | if ($(‘#keks').html().trim()) {
}
|
Copy after login
10. How to find the index number of an element from an unsorted set
1 | $( "ul > li" ).click( function () { var index = $(this).prevAll().length; });
|
Copy after login
11. How to bind functions to events
1 | $( '#foo' ).bind( 'click' , function () { alert( 'User clicked on "foo."' ); });
|
Copy after login
12. How to append or add html to elements
1 | $(‘#lal ').append(‘sometext' );
|
Copy after login
13. How to use object literals to define attributes when creating elements
1 | var e = $(“”, { href: “#”, class : “a- class another- class ”, title: “…” });
|
Copy after login
14. How to use multiple attributes to filter
1 2 | var elements = $( '#someid input[type=sometype][value=somevalue]' ).get();
|
Copy after login
15. How to use jQuery to preload images
1 2 | jQuery.preloadImages = function () { for ( var i = 0; i < arguments.length; i++) { $( "<img />" ).attr( 'src' , arguments[i]); } };
|
Copy after login
16. How to set an event handler for any element that matches the selector
1 | $( 'button.someClass' ).live( 'click' , someFunction);
|
Copy after login
17. How to find an option element that has been selected
1 | $(‘#someElement ').find(‘option:selected' );
|
Copy after login
18. How to hide an element that contains a certain value text
1 | $(“p.value:contains(‘thetextvalue')”).hide();
|
Copy after login
19. If you automatically scroll to a certain area on the page
1 2 3 4 5 6 7 8 9 | jQuery.fn.autoscroll = function (selector) {
$(‘html,body').animate( { scrollTop: $(this ).offset().top },
500
);
}
$(‘.area_name').autoscroll();
|
Copy after login
20. How to detect various browsers
1 2 3 4 | if ( $.browser.safari)
if ($.browser.msie && $.browser.version > 6 )
if ($.browser.msie && $.browser.version <= 6 )
if ($.browser.mozilla && $.browser.version >= ‘1.8' )
|
Copy after login
21. How to replace words in a string
1 | var el = $(‘#id'); el.html(el.html().replace(/word/ig, ”));
|
Copy after login
22. How to disable right-click context menu
1 2 3 4 | $(document).bind(‘contextmenu', function (e) {
return false ;
});
|
Copy after login
23. How to define a custom selector
1 | $.expr[ ':' ].mycustomselector = function (element, index, meta, stack){
|
Copy after login
24. How to check if an element exists
1 2 3 | if ($(‘#someDiv' ).length) {
}
|
Copy after login
25. How to use jQuery to detect right and left mouse clicks
1 | $( "#someelement" ).live( 'click' , function (e) { if ((!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1)) { alert( "Left Mouse Button Clicked" ); } else if (e.button == 2) { alert( "Right Mouse Button Clicked" ); } });
|
Copy after login
26. How to display or delete the default value in the input field
1 2 | $( ".swap" ).each( function (i) { wap_val[i] = $(this).val(); $(this).focusin( function () { if ($(this).val() == swap_val[i]) { $(this).val( "" ); } }).focusout( function () { if ($.trim($(this).val()) == "" ) { $(this).val(swap_val[i]); } }); });
|
Copy after login
27. How to automatically hide or close elements after a period of time (supports version 1.4)
1 2 | setTimeout( function () { $( '.mydiv' ).hide( 'blind' , {}, 500) }, 5000);
|
Copy after login
28. How to dynamically add created elements to DOM
1 2 | var newDiv = $(”);
newDiv.attr(‘id ', ‘myNewDiv' ).appendTo(‘body');
|
Copy after login
29. How to limit the number of characters in the "Text-Area" field
1 2 | jQuery.fn.maxLength = function (max) { this.each( function () { var type = this.tagName.toLowerCase(); var inputType = this.type ? this.type.toLowerCase() : null; if (type == "input" && inputType == "text" || inputType == "password" ) { this.maxLength = max; } else if (type == "textarea" ) { this.onkeypress = function (e) { var ob = e || event; var keyCode = ob.keyCode; var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd; return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection); }; this.onkeyup = function () { if (this.value.length > max) { this.value = this.value.substring(0, max); } }; } }); };
|
Copy after login
30. How to create a basic test for a function
31. How to clone an element in jQuery
1 | var cloned = $(‘#somediv'). clone ();
|
Copy after login
32. How to test whether an element is visible in jQuery
1 2 3 | if ($(element).is(‘:visible') ) {
}
|
Copy after login
33. How to place an element in the center of the screen
1 2 3 4 | jQuery.fn.center = function () { this.css( 'position' , 'absolute' ); this.css( 'top' , ($(window).height() - this.height())
/ +$(window).scrollTop() + 'px' ); this.css( 'left' , ($(window).width() - this.width())
/ 2 + $(window).scrollLeft() + 'px' ); return this; }
|
Copy after login
34. How to put the values of all elements with a specific name into an array
1 2 3 4 | var arrInputValues = new Array();
$(“input[name= 'table[]' ]”).each( function () {
arrInputValues.push($(this ).val());
});
|
Copy after login
35. How to remove HTML from an element
1 2 | ( function ($) { $.fn.stripHtml = function () { var regexp = /<( "[^" ]* "|'[^']*'|[^'" >])*>/gi; this.each( function () { $(this).html($(this).html().replace(regexp, "" )); }); return $(this); } })(jQuery);
|
Copy after login
36. How to use closest to get the parent element
1 | $(‘#searchBox ').closest(‘div' );
|
Copy after login
37. How to log jQuery events using Firebug and Firefox
38. How to force a link to open in a pop-up window
1 | jQuery( 'a.popup' ).live( 'click' , function () { newwindow = window.open($(this).attr( 'href' ), '' , 'height=200,width=150' ); if (window.focus) { newwindow.focus(); } return false; });
|
Copy after login
39. How to force a link to open in a new tab
1 | jQuery( 'a.newTab' ).live( 'click' , function () { newwindow = window.open($(this).href); jQuery(this).target = "_blank" ; return false; });
|
Copy after login
40. 在jQuery中如何使用.siblings()来选择同辈元素
1 2 3 4 |
$( '#nav li' ).click( function () { $( '#nav li' ).removeClass( 'active' ); $(this).addClass( 'active' ); });
$( '#nav li' ).click( function () { $(this).addClass( 'active' ).siblings().removeClass( 'active' ); })
|
Copy after login
41. 如何切换页面上的所有复选框
1 2 3 | var tog = false ;
$( 'a' ).click( function () { $( "input[type=checkbox]" ).attr( "checked" , !tog); tog = !tog; });
|
Copy after login
42. 如何基于一些输入文本来过滤一个元素列表
1 2 | $( '.someClass' ).filter( function () { return $(this).attr( 'value' ) == $( 'input#someId' ).val(); })
|
Copy after login
43. 如何获得鼠标垫光标位置x和y
1 | $(document).ready( function () { $(document).mousemove( function (e) { $( '#XY' ).html( "X Axis : " + e.pageX + " | Y Axis " + e.pageY); }); });
|
Copy after login
44. 如何把整个的列表元素(List Element,LI)变成可点击的
1 2 | $( "ul li" ).click( function () { window.location = $(this).find( "a" ).attr( "href" ); return false; });
<ul> <li><a href= "#" >Link 1</a></li> <li><a href= "#" >Link 2</a></li> <li><a href= "#" >Link 3</a></li> <li><a href= "#" >Link 4</a></li> </ul>
|
Copy after login
45. 如何使用jQuery来解析XML(基本的例子)
46. 如何检查图像是否已经被完全加载进来
1 | $( '#theImage' ).attr( 'src' , 'image.jpg' ).load( function () { alert( 'This Image Has Been Loaded' ); });
|
Copy after login
47. 如何使用jQuery来为事件指定命名空间
48. 如何检查cookie是否启用
1 | var dt = new Date (); dt.setSeconds(dt.getSeconds() + 60); document.cookie = "cookietest=1; expires=" + dt.toGMTString(); var cookiesEnabled = document.cookie.indexOf( "cookietest=" ) != -1; if (!cookiesEnabled) {
|
Copy after login
49. 如何让cookie过期
1 | var date = new Date (); date .setTime( date .getTime() + (x * 60 * 1000)); $.cookie( 'example' , 'foo' , { expires: date });
|
Copy after login
50. 如何使用一个可点击的链接来替换页面中任何的URL
1 2 | $.fn.replaceUrl = function () { var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi; this.each( function () { $(this).html( $(this).html().replace(regexp, '<a href="$1">$1</a>' ) ); }); return $(this); }
|
Copy after login
以上内容就是给大家介绍了web前端开发JQuery常用实例代码片段(50个),希望大家喜欢。