偶然在網上看到這些不錯的jQuery代碼開發技巧。原文收集了30個,另外查找的時候發現了還有20個。加上另外十個實用的jQuery代碼片段,共60個代碼技巧,收集在一起分享給大家。
這些jQuery代碼實用性比較強,有些忘了的地方可以現學現用。現在暫時沒有用到以後應該會用到,覺得不錯可以收藏一下。當然,覺得還不過癮的可以去看看:
1. 創建一個嵌套的過濾器
- .filter(":not(:has(.selected))") //去掉所有不包含class爲.selected的元素
2. 重用你的元素查詢
- var allItems = $("div.item");
- var keepList = $("div#container1 div.item");
- <div>class names:
- $(formToLookAt + " input:checked").each(function() { keepListkeepList = keepList.filter("." + $(this).attr("name")); });
- </div>
3. 使用has()來判斷一個元素是否包含特定的class或者元素
- //jQuery 1.4.* includes support for the has method. This method will find
- //if a an element contains a certain other element class or whatever it is
- //you are looking for and do anything you want to them.
- $("input").has(".email").addClass("email_icon");
4. 使用jQuery切換樣式
- //Look for the media-type you wish to switch then set the href to your new style sheet
- $('link[media='screen']').attr('href', 'Alternative.css');
5. 限制選擇的區域
- //Where possible, pre-fix your class names with a tag name
- //so that jQuery doesn't have to spend more time searching
- //for the element you're after. Also remember that anything
- //you can do to be more specific about where the element is
- //on your page will cut down on execution/search times
- var in_stock = $('#shopping_cart_items input.is_in_stock');
- <ul id="shopping_cart_items">
- <li>
- <input value="Item-X" name="item" class="is_in_stock" type="radio"> Item X</li>
- <li>
- <input value="Item-Y" name="item" class="3-5_days" type="radio"> Item Y</li>
- <li>
- <input value="Item-Z" name="item" class="unknown" type="radio"> Item Z</li>
- </ul>
6. 如何正確使用ToggleClass
- //Toggle class allows you to add or remove a class
- //from an element depending on the presence of that
- //class. Where some developers would use:
- a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton');
- //toggleClass allows you to easily do this using
- a.toggleClass('blueButton');
7. 設置IE指定的功能
- if ($.browser.msie) { // Internet Explorer is a sadist. }
8. 使用jQuery來替換一個元素
- $('#thatdiv').replaceWith('fnuh');
9. 驗證一個元素是否爲空
- if ($('#keks').html()) { //Nothing found ;}
10. 在無序的set中查找一個元素的索引
- $("ul > li").click(function () {
- var index = $(this).prevAll().length;
- });
11. 綁定一個函數到一個事件
- $('#foo').bind('click', function() {
- alert('User clicked on "foo."');
- });
12. 添加HTML到一個元素
- $('#lal').append('sometext');
13. 創建元素時使用對象來定義屬性
- var e = $("", { href: "#", class: "a-class another-class", title: "..." });
14. 使用過濾器過濾多屬性
- //This precision-based approached can be useful when you use
- //lots of similar input elements which have different types
- var elements = $('#someid input[type=sometype][value=somevalue]').get();
15. 使用jQuery預加載圖片
- jQuery.preloadImages = function() { for(var i = 0; i').attr('src', arguments[i]); } };
- // Usage $.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg');
16. 設置任何匹配一個選擇器的事件處理程序
- $('button.someClass').live('click', someFunction);
- //Note that in jQuery 1.4.2, the delegate and undelegate options have been
- //introduced to replace live as they offer better support for context
- //For example, in terms of a table where before you would use..
- // .live()
- $("table").each(function(){
- $("td", this).live("hover", function(){
- $(this).toggleClass("hover");
- });
- });
- //Now use..
- $("table").delegate("td", "hover", function(){
- $(this).toggleClass("hover");
- });
17. 找到被選擇到的選項(option)元素
- $('#someElement').find('option:selected');
18. 隱藏包含特定值的元素
- $("p.value:contains('thetextvalue')").hide();
19. 自動的滾動到頁面特定區域
- jQuery.fn.autoscroll = function(selector) {
- $('html,body').animate(
- {scrollTop: $(selector).offset().top},
- 500
- );
- }
- //Then to scroll to the class/area you wish to get to like this:
- $('.area_name').autoscroll();
20. 檢測各種瀏覽器
- Detect Safari (if( $.browser.safari)),
- Detect IE6 and over (if ($.browser.msie && $.browser.version > 6 )),
- Detect IE6 and below (if ($.browser.msie && $.browser.version <= 6 )),
- Detect FireFox 2 and above (if ($.browser.mozilla && $.browser.version >= '1.8' ))
21. 替換字符串中的單詞
- var el = $('#id');
- el.html(el.html().replace(/word/ig, ''));
22. 關閉右鍵的菜單
- $(document).bind('contextmenu',function(e){ return false; });
23. 定義一個定製的選擇器
- $.expr[':'].mycustomselector = function(element, index, meta, stack){
- // element- is a DOM element
- // index - the current loop index in stack
- // meta - meta data about your selector
- // stack - stack of all elements to loop
- // Return true to include current element
- // Return false to explude current element
- };
- // Custom Selector usage:
- $('.someClasses:test').doSomething();
24. 判斷一個元素是否存在
- if ($('#someDiv').length) {//hooray!!! it exists...}
25. 使用jQuery判斷鼠標的左右鍵點擊
- $("#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");
- });
26. 顯示或者刪除輸入框的缺省值
- //This snippet will show you how to keep a default value
- //in a text input field for when a user hasn't entered in
- //a value to replace it
- swap_val = [];
- $(".swap").each(function(i){
- swap_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]);
- }
- });
- });
- <INPUT class=swap value="Enter Username here.." type=text>
27. 指定時間後自動隱藏或者關閉元素(1.4支持)
- //Here's how we used to do it in 1.3.2 using setTimeout
- setTimeout(function() {
- $('.mydiv').hide('blind', {}, 500)
- }, 5000);
- //And here's how you can do it with 1.4 using the delay() feature (this is a lot like sleep)
- $(".mydiv").delay(5000).hide('blind', {}, 500);
28. 動態創建元素到DOM
- var newgbin1Div = $('');
- newgbin1Div.attr('id','gbin1.com').appendTo('body');
29. 限制textarea的字符數量
- 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"){
- //Apply the standard maxLength
- 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);
- }
- };
- }
- });
- };
- //Usage:
- $('#gbin1textarea').maxLength(500);
30. 爲函數創建一個基本測試用例
- //Separate tests into modules.
- module("Module B");
- test("some other gbin1.com test", function() {
- //Specify how many assertions are expected to run within a test.
- expect(2);
- //A comparison assertion, equivalent to JUnit's assertEquals.
- equals( true, false, "failing test" );
- equals( true, true, "passing test" );
- });
31. 使用jQuery克隆元素
- var cloned = $('#gbin1div').clone();
32. 測試一個元素在jQuery中是否可見
- if($(element).is(':visible') == 'true') { //The element is Visible }
33. 元素屏幕居中
- 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;
- }
- //Use the above function as: $('#gbin1div').center();
34. 使用特定名字的元素對應的值生成一個數組
- var arrInputValues = new Array();
- $("input[name='table[]']").each(function(){
- arrInputValues.push($(this).val());
- });
35. 剔除元素中的HTML
- (function($) {
- $.fn.stripHtml = function() {
- var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
- this.each(function() {
- $(this).html(
- $(this).html().replace(regexp,"")
- );
- });
- return $(this);
- }
- })(jQuery);
- //usage:
- $('p').stripHtml();
36. 使用closest來得到父元素
- $('#searchBox').closest('div');
37. 使用firebug來記錄jQuery事件
- // Allows chainable logging
- // Usage: $('#someDiv').hide().log('div hidden').addClass('someClass');
- jQuery.log = jQuery.fn.log = function (msg) {
- if (console){
- console.log("%s: %o", msg, this);
- }
- return this;
- };
38. 點擊鏈接強制彈出新窗口
- jQuery('a.popup').live('click', function(){
- newwindow=window.open($(this).attr('href'),'','height=200,width=150');
- if (window.focus) {newwindow.focus()}
- return false;
- });
39. 點擊鏈接強制打開新標籤頁
- jQuery('a.newTab').live('click', function(){
- newwindow=window.open($(this).href);
- jQuery(this).target = "_blank";
- return false;
- });
40. 使用siblings()來處理同類元素
- // Rather than doing this
- $('#nav li').click(function(){
- $('#nav li').removeClass('active');
- $(this).addClass('active');
- });
- // Do this instead
- $('#nav li').click(function(){
- $(this).addClass('active')
- .siblings().removeClass('active');
- });
41. 選擇或者不選頁面上全部複選框
- var tog = false; // or true if they are checked on load
- $('a').click(function() {
- $("input[type=checkbox]").attr("checked",!tog);
- tog = !tog;
- });
42. 基於輸入文字過濾頁面元素
- //If the value of the element matches that of the entered text
- //it will be returned
- $('.gbin1Class').filter(function() {
- return $(this).attr('value') == $('input#gbin1Id').val() ;
- })
43. 取得鼠標的X和Y座標
- $(document).mousemove(function(e){
- $(document).ready(function() {
- $().mousemove(function(e){
- $('#XY').html("Gbin1 X Axis : " + e.pageX + " | Gbin1 Y Axis " + e.pageY);
- });
- });
44. 使得整個列表元素(LI)可點擊
- $("ul li").click(function(){
- window.location=$(this).find("a").attr("href"); return false;
- });
- <UL>
- <LI><A href="#">GBin1 Link 1</A></LI>
- <LI><A href="#">GBin1 Link 2</A></LI>
- <LI><A href="#">GBin1 Link 3</A></LI>
- <LI><A href="#">GBin1 Link 4</A></LI>
- </UL>
45. 使用jQuery來解析XML
- function parseXml(xml) {
- //find every Tutorial and print the author
- $(xml).find("Tutorial").each(function()
- {
- $("#output").append($(this).attr("author") + "");
- });
- }
46. 判斷一個圖片是否加載完全
- $('#theGBin1Image').attr('src', 'image.jpg').load(function() {
- alert('This Image Has Been Loaded');
- });
47. 使用jQuery命名事件
- //Events can be namespaced like this
- $('input').bind('blur.validation', function(e){
- // ...
- });
- //The data method also accept namespaces
- $('input').data('validation.isValid', true);
48. 判斷cookie是否激活或者關閉
- 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)
- {
- //cookies have not been enabled
- }
49. 強制過期cookie
- var date = new Date();
- date.setTime(date.getTime() + (x * 60 * 1000));
- $.cookie('example', 'foo', { expires: date });
50. 使用一個可點擊的鏈接替換頁面中所有URL
- $.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);
- }
- //usage
- $('#GBin1div').replaceUrl();
51: 在表單中禁用“回車鍵”
大家可能在表單的操作中需要防止用戶意外的提交表單,那麼下面這段代碼肯定非常有幫助:
- $("#form").keypress(function(e) {
- if (e.which == 13) {
- return false;
- }
- });
52: 清除所有的表單數據
可能針對不同的表單形式,你需要調用不同類型的清楚方法,不過使用下面這個現成方法,絕對能讓你省不少功夫。
- function clearForm(form) {
- // iterate over all of the inputs for the form
- // element that was passed in
- $(':input', form).each(function() {
- var type = this.type;
- var tag = this.tagName.toLowerCase(); // normalize case
- // it's ok to reset the value attr of text inputs,
- // password inputs, and textareas
- if (type == 'text' || type == 'password' || tag == 'textarea')
- this.value = "";
- // checkboxes and radios need to have their checked state cleared
- // but should *not* have their 'value' changed
- else if (type == 'checkbox' || type == 'radio')
- this.checked = false;
- // select elements need to have their 'selectedIndex' property set to -1
- // (this works for both single and multiple select elements)
- else if (tag == 'select')
- this.selectedIndex = -1;
- });
- };
53: 將表單中的按鈕禁用
下面的代碼對於ajax操作非常有用,你可以有效的避免用戶多次提交數據,個人也經常使用:
禁用按鈕:
- $("#somebutton").attr("disabled", true);
啓動按鈕:
- $("#submit-button").removeAttr("disabled");
可能大家往往會使用.attr(‘disabled’,false);,不過這是不正確的調用。
54: 輸入內容後啓用遞交按鈕
這個代碼和上面類似,都屬於幫助用戶控制表單遞交按鈕。使用這段代碼後,遞交按鈕只有在用戶輸入指定內容後纔可以啓動。
- $('#username').keyup(function() {
- $('#submit').attr('disabled', !$('#username').val());
- });
55: 禁止多次遞交表單
多次遞交表單對於web應用來說是個比較頭疼的問題,下面的代碼能夠很好的幫助你解決這個問題:
- $(document).ready(function() {
- $('form').submit(function() {
- if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
- jQuery.data(this, "disabledOnSubmit", { submited: true });
- $('input[type=submit], input[type=button]', this).each(function() {
- $(this).attr("disabled", "disabled");
- });
- return true;
- }
- else
- {
- return false;
- }
- });
- });
56: 高亮顯示目前聚焦的輸入框標示
有時候你需要提示用戶目前操作的輸入框,你可以使用下面代碼高亮顯示標示:
- $("form :input").focus(function() {
- $("label[for='" + this.id + "']").addClass("labelfocus");
- }).blur(function() {
- $("label").removeClass("labelfocus");
- });
57: 動態方式添加表單元素
這個方法可以幫助你動態的添加表單中的元素,比如,input等:
- //change event on password1 field to prompt new input
- $('#password1').change(function() {
- //dynamically create new input and insert after password1
- $("#password1").append("<input type='text' name='password2' id='password2' />");
- });
58: 自動將數據導入selectbox中
下面代碼能夠使用ajax數據自動生成選擇框的內容
- $(function(){
- $("select#ctlJob").change(function(){
- $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
- var options = '';
- for (var i = 0; i < j.length; i++) {
- options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
- }
- $("select#ctlPerson").html(options);
- })
- })
- })
59: 判斷一個複選框是否被選中
代碼很簡單,如下:
- $('#checkBox').attr('checked');
60: 使用代碼來遞交表單
代碼很簡單,如下:
- $("#myform").submit();
希望大家覺得這些jQuery代碼會對你的開發有幫助,如果你也有類似的jQuery代碼或者jQuery插件,歡迎一起分享!
注:部分代碼原文應該是英文的。但是看見轉的幾個鏈接已經打不開了。所以就這樣吧。
轉載請註明:欲思博客 » 60個很實用的jQuery代碼開發技巧收集