{"action":"opened","issue":{"url":"https://api.github.com/repos/confidence68/blog/issues/104","labels_url":"https://api.github.com/repos/confidence68/blog/issues/104/labels{/name}","comments_url":"https://api.github.com/repos/confidence68/blog/issues/104/comments","events_url":"https://api.github.com/repos/confidence68/blog/issues/104/events","html_url":"https://github.com/confidence68/blog/issues/104","id":92815014,"number":104,"title":"jQuery代码开发技巧收集,jquery常用的开发代码","user":{"login":"confidence68","id":3736355,"avatar_url":"https://avatars.githubusercontent.com/u/3736355?v=3","gravatar_id":"","url":"https://api.github.com/users/confidence68","html_url":"https://github.com/confidence68","followers_url":"https://api.github.com/users/confidence68/followers","following_url":"https://api.github.com/users/confidence68/following{/other_user}","gists_url":"https://api.github.com/users/confidence68/gists{/gist_id}","starred_url":"https://api.github.com/users/confidence68/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/confidence68/subscriptions","organizations_url":"https://api.github.com/users/confidence68/orgs","repos_url":"https://api.github.com/users/confidence68/repos","events_url":"https://api.github.com/users/confidence68/events{/privacy}","received_events_url":"https://api.github.com/users/confidence68/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"milestone":null,"comments":0,"created_at":"2015-07-03T07:43:20Z","updated_at":"2015-07-03T07:43:20Z","closed_at":null,"body":"<h2>jQuery代码开发技巧收集,jquery常用的开发代码</h2>\r\n\r\n今天分享一个jquery常用的开发代码，大部分是网友总结的，总共60条。后期我也会陆续完善！ 把我在开发中常用的写在这里，希望持续关注~~\r\n\r\n**1. 使用siblings()来处理同类元素**\r\n\r\n    // Rather than doing this\r\n    $('#nav li').click(function(){\r\n        $('#nav li').removeClass('active');\r\n        $(this).addClass('active');\r\n    });\r\n    // Do this instead\r\n    $('#nav li').click(function(){\r\n        $(this).addClass('active').siblings().removeClass('active');\r\n    });\r\n\r\n**2. 选择或者不选页面上全部复选框**\r\n\r\n    var tog = false; // or true if they are checked on load\r\n    $('a').click(function() {\r\n        $(\"input[type=checkbox]\").attr(\"checked\",!tog);\r\n        tog = !tog;\r\n    });\r\n\r\n**3. 基于输入文字过滤页面元素**\r\n\r\n    //If the value of the element matches that of the entered text\r\n    //it will be returned\r\n    $('.gbin1Class').filter(function() {\r\n        return $(this).attr('value') == $('input#gbin1Id').val() ;\r\n     })\r\n\r\n**4. 取得鼠标的X和Y坐标**\r\n\r\n    $(document).mousemove(function(e){\r\n    $(document).ready(function() {\r\n    $().mousemove(function(e){\r\n    $('#XY').html(\"Gbin1 X Axis : \" + e.pageX + \" | Gbin1 Y Axis \" + e.pageY);\r\n    });\r\n    });\r\n\r\n**5. 使得整个列表元素(LI)可点击**\r\n\r\n    $(\"ul li\").click(function(){\r\n      window.location=$(this).find(\"a\").attr(\"href\"); return false;\r\n    });\r\n    <UL>\r\n    <LI><A href=\"#\">GBin1 Link 1</A></LI>\r\n    <LI><A href=\"#\">GBin1 Link 2</A></LI>\r\n    <LI><A href=\"#\">GBin1 Link 3</A></LI>\r\n    <LI><A href=\"#\">GBin1 Link 4</A></LI>\r\n    </UL>\r\n\r\n \r\n**6. 使用jQuery来解析XML**\r\n\r\n    function parseXml(xml) {\r\n      //find every Tutorial and print the author\r\n      $(xml).find(\"Tutorial\").each(function()\r\n      {\r\n      $(\"#output\").append($(this).attr(\"author\") + \"\");\r\n      });\r\n    }\r\n\r\n**7. 判断一个图片是否加载完全**\r\n\r\n    $('#theGBin1Image').attr('src', 'image.jpg').load(function() {\r\n    alert('This Image Has Been Loaded');\r\n    });\r\n\r\n**8. 使用jQuery命名事件**\r\n\r\n    //Events can be namespaced like this\r\n    $('input').bind('blur.validation', function(e){\r\n        // ...\r\n    });\r\n    //The data method also accept namespaces\r\n    $('input').data('validation.isValid', true);\r\n\r\n**9. 判断cookie是否激活或者关闭**\r\n\r\n    var dt = new Date();\r\n    dt.setSeconds(dt.getSeconds() + 60);\r\n    document.cookie = \"cookietest=1; expires=\" + dt.toGMTString();\r\n    var cookiesEnabled = document.cookie.indexOf(\"cookietest=\") != -1;\r\n    if(!cookiesEnabled)\r\n    {\r\n      //cookies have not been enabled\r\n    }\r\n\r\n**10.强制过期cookie**\r\n\r\n    var date = new Date();\r\n    date.setTime(date.getTime() + (x * 60 * 1000));\r\n    $.cookie('example', 'foo', { expires: date });\r\n\r\n**11. 使用一个可点击的链接替换页面中所有URL**\r\n\r\n    $.fn.replaceUrl = function() {\r\n            var regexp = /((ftp|http|https)://(w+:{0,1}w*@)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%@!-/]))?)/gi;\r\n            this.each(function() {\r\n                $(this).html(\r\n                    $(this).html().replace(regexp,'<A href=\"$1\">$1</A>')\r\n                );\r\n            });\r\n            return $(this);\r\n        }\r\n    //usage\r\n    $('#GBin1div').replaceUrl(); \r\n\r\n**12. 在表单中禁用“回车键”**\r\n\r\n大家可能在表单的操作中需要防止用户意外的提交表单，那么下面这段代码肯定非常有帮助：\r\n\r\n    $(\"#form\").keypress(function(e) {\r\n      if (e.which == 13) {\r\n        return false;\r\n      }\r\n    });\r\n\r\n<!--more-->\r\n\r\n\r\n**13. 清除所有的表单数据**\r\n\r\n可能针对不同的表单形式，你需要调用不同类型的清楚方法，不过使用下面这个现成方法，绝对能让你省不少功夫。\r\n\r\n    function clearForm(form) {\r\n      // iterate over all of the inputs for the form\r\n      // element that was passed in\r\n      $(':input', form).each(function() {\r\n        var type = this.type;\r\n        var tag = this.tagName.toLowerCase(); // normalize case\r\n        // it's ok to reset the value attr of text inputs,\r\n        // password inputs, and textareas\r\n        if (type == 'text' || type == 'password' || tag == 'textarea')\r\n          this.value = \"\";\r\n        // checkboxes and radios need to have their checked state cleared\r\n        // but should *not* have their 'value' changed\r\n        else if (type == 'checkbox' || type == 'radio')\r\n          this.checked = false;\r\n        // select elements need to have their 'selectedIndex' property set to -1\r\n        // (this works for both single and multiple select elements)\r\n        else if (tag == 'select')\r\n          this.selectedIndex = -1;\r\n      });\r\n    };\r\n\r\n**14. 将表单中的按钮禁用**\r\n\r\n下面的代码对于ajax操作非常有用，你可以有效的避免用户多次提交数据，个人也经常使用：\r\n\r\n禁用按钮：\r\n\r\n    $(\"#somebutton\").attr(\"disabled\", true);\r\n\r\n启动按钮：\r\n\r\n    $(\"#submit-button\").removeAttr(\"disabled\");\r\n\r\n可能大家往往会使用.attr(‘disabled’,false);，不过这是不正确的调用。\r\n\r\n**15. 输入内容后启用递交按钮**\r\n\r\n这个代码和上面类似，都属于帮助用户控制表单递交按钮。使用这段代码后，递交按钮只有在用户输入指定内容后才可以启动。\r\n\r\n    $('#username').keyup(function() {\r\n        $('#submit').attr('disabled', !$('#username').val()); \r\n    });\r\n\r\n**16.禁止多次递交表单**\r\n\r\n多次递交表单对于web应用来说是个比较头疼的问题，下面的代码能够很好的帮助你解决这个问题：\r\n\r\n    $(document).ready(function() {\r\n      $('form').submit(function() {\r\n        if(typeof jQuery.data(this, \"disabledOnSubmit\") == 'undefined') {\r\n          jQuery.data(this, \"disabledOnSubmit\", { submited: true });\r\n          $('input[type=submit], input[type=button]', this).each(function() {\r\n            $(this).attr(\"disabled\", \"disabled\");\r\n          });\r\n          return true;\r\n        }\r\n        else\r\n        {\r\n          return false;\r\n        }\r\n      });\r\n    });\r\n\r\n**17. 高亮显示目前聚焦的输入框标示**\r\n\r\n有时候你需要提示用户目前操作的输入框，你可以使用下面代码高亮显示标示：\r\n\r\n    $(\"form :input\").focus(function() {\r\n      $(\"label[for='\" + this.id + \"']\").addClass(\"labelfocus\");\r\n    }).blur(function() {\r\n      $(\"label\").removeClass(\"labelfocus\");\r\n    });\r\n\r\n**18. 动态方式添加表单元素**\r\n\r\n这个方法可以帮助你动态的添加表单中的元素，比如，input等：\r\n\r\n    //change event on password1 field to prompt new input\r\n    $('#password1').change(function() {\r\n            //dynamically create new input and insert after password1\r\n            $(\"#password1\").append(\"<input type='text' name='password2' id='password2' />\");\r\n    });\r\n\r\n**19. 自动将数据导入selectbox中**\r\n\r\n下面代码能够使用ajax数据自动生成选择框的内容\r\n\r\n    $(function(){\r\n      $(\"select#ctlJob\").change(function(){\r\n        $.getJSON(\"/select.php\",{id: $(this).val(), ajax: 'true'}, function(j){\r\n          var options = '';\r\n          for (var i = 0; i < j.length; i++) {\r\n            options += '<option value=\"' + j[i].optionValue + '\">' + j[i].optionDisplay + '</option>';\r\n          }\r\n          $(\"select#ctlPerson\").html(options);\r\n        })\r\n      })\r\n    })\r\n\r\n**20.判断一个复选框是否被选中**\r\n\r\n代码很简单，如下：\r\n\r\n    $('#checkBox').attr('checked');\r\n\r\n**21. 使用代码来递交表单**\r\n\r\n代码很简单，如下：\r\n\r\n    $(\"#myform\").submit();\r\n\r\n**22. 创建一个嵌套的过滤器**\r\n\r\n    .filter(\":not(:has(.selected))\") //去掉所有不包含class为.selected的元素\r\n\r\n**23. 重用你的元素查询**\r\n\r\n    var allItems = $(\"div.item\");  \r\n    var keepList = $(\"div#container1 div.item\"); \r\n    <div>class names: \r\n    $(formToLookAt + \" input:checked\").each(function() {     keepListkeepList = keepList.filter(\".\" + $(this).attr(\"name\")); });\r\n    </div>\r\n\r\n**24. 使用has()来判断一个元素是否包含特定的class或者元素**\r\n\r\n    //jQuery 1.4.* includes support for the has method. This method will find  \r\n    //if a an element contains a certain other element class or whatever it is  \r\n    //you are looking for and do anything you want to them. \r\n    $(\"input\").has(\".email\").addClass(\"email_icon\");\r\n\r\n**25. 使用jQuery切换样式**\r\n\r\n    //Look for the media-type you wish to switch then set the href to your new style sheet  \r\n    $('link[media='screen']').attr('href', 'Alternative.css');  \r\n\r\n**26. 限制选择的区域**\r\n\r\n    //Where possible, pre-fix your class names with a tag name  \r\n    //so that jQuery doesn't have to spend more time searching  \r\n    //for the element you're after. Also remember that anything  \r\n    //you can do to be more specific about where the element is  \r\n    //on your page will cut down on execution/search times  \r\n    var in_stock = $('#shopping_cart_items input.is_in_stock');\r\n    <ul id=\"shopping_cart_items\">  \r\n    <li>  \r\n    <input value=\"Item-X\" name=\"item\" class=\"is_in_stock\" type=\"radio\"> Item X</li>  \r\n    <li>  \r\n    <input value=\"Item-Y\" name=\"item\" class=\"3-5_days\" type=\"radio\"> Item Y</li>  \r\n    <li>  \r\n    <input value=\"Item-Z\" name=\"item\" class=\"unknown\" type=\"radio\"> Item Z</li>  \r\n    </ul> \r\n\r\n**27. 如何正确使用ToggleClass**\r\n\r\n    //Toggle class allows you to add or remove a class  \r\n    //from an element depending on the presence of that  \r\n    //class. Where some developers would use:  \r\n    a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton');  \r\n    //toggleClass allows you to easily do this using  \r\n    a.toggleClass('blueButton'); \r\n\r\n**28. 设置IE指定的功能**\r\n\r\n    if ($.browser.msie) { // Internet Explorer is a sadist. } \r\n\r\n**29. 使用jQuery来替换一个元素**\r\n\r\n    $('#thatdiv').replaceWith('fnuh');\r\n\r\n**30. 验证一个元素是否为空**\r\n\r\n    if ($('#keks').html()) { //Nothing found ;}  \r\n\r\n**31. 在无序的set中查找一个元素的索引**\r\n\r\n    $(\"ul > li\").click(function () {  \r\n        var index = $(this).prevAll().length;  \r\n    });\r\n\r\n**32. 绑定一个函数到一个事件**\r\n\r\n    $('#foo').bind('click', function() {  \r\n      alert('User clicked on \"foo.\"');  \r\n    }); \r\n\r\n**33. 添加HTML到一个元素**\r\n\r\n    $('#lal').append('sometext');\r\n\r\n**34. 创建元素时使用对象来定义属性**\r\n\r\n    var e = $(\"\", { href: \"#\", class: \"a-class another-class\", title: \"...\" });\r\n\r\n**35. 使用过滤器过滤多属性**\r\n\r\n    //This precision-based approached can be useful when you use  \r\n    //lots of similar input elements which have different types  \r\n    var elements = $('#someid input[type=sometype][value=somevalue]').get(); \r\n\r\n**36. 使用jQuery预加载图片**\r\n\r\n    jQuery.preloadImages = function() { for(var i = 0; i').attr('src', arguments[i]); } };  \r\n    // Usage $.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg');   \r\n\r\n**37. 设置任何匹配一个选择器的事件处理程序**\r\n\r\n    $('button.someClass').live('click', someFunction);\r\n      //Note that in jQuery 1.4.2, the delegate and undelegate options have been\r\n      //introduced to replace live as they offer better support for context\r\n        //For example, in terms of a table where before you would use..\r\n      // .live()\r\n      $(\"table\").each(function(){\r\n        $(\"td\", this).live(\"hover\", function(){\r\n        $(this).toggleClass(\"hover\");\r\n        });\r\n      });\r\n      //Now use..\r\n      $(\"table\").delegate(\"td\", \"hover\", function(){\r\n      $(this).toggleClass(\"hover\");\r\n    });\r\n\r\n**38. 找到被选择到的选项(option)元素**\r\n\r\n    $('#someElement').find('option:selected');\r\n\r\n**39. 隐藏包含特定值的元素**\r\n\r\n    $(\"p.value:contains('thetextvalue')\").hide();\r\n\r\n**40. 自动的滚动到页面特定区域**\r\n\r\n    jQuery.fn.autoscroll = function(selector) {\r\n      $('html,body').animate(\r\n        {scrollTop: $(selector).offset().top},\r\n        500\r\n      );\r\n    }\r\n    //Then to scroll to the class/area you wish to get to like this:\r\n    $('.area_name').autoscroll();\r\n\r\n**42. 检测各种浏览器**\r\n\r\n    Detect Safari (if( $.browser.safari)),\r\n    Detect IE6 and over (if ($.browser.msie && $.browser.version > 6 )),\r\n    Detect IE6 and below (if ($.browser.msie && $.browser.version <= 6 )),\r\n    Detect FireFox 2 and above (if ($.browser.mozilla && $.browser.version >= '1.8' ))\r\n\r\n**42. 替换字符串中的单词**\r\n\r\n    var el = $('#id');\r\n    el.html(el.html().replace(/word/ig, ''));\r\n\r\n**43. 关闭右键的菜单**\r\n\r\n    $(document).bind('contextmenu',function(e){ return false; });\r\n\r\n**44. 定义一个定制的选择器**\r\n\r\n    $.expr[':'].mycustomselector = function(element, index, meta, stack){\r\n    // element- is a DOM element\r\n    // index - the current loop index in stack\r\n    // meta - meta data about your selector\r\n    // stack - stack of all elements to loop\r\n    // Return true to include current element\r\n    // Return false to explude current element\r\n    };\r\n    // Custom Selector usage:\r\n    $('.someClasses:test').doSomething();\r\n\r\n**45. 判断一个元素是否存在**\r\n\r\n    if ($('#someDiv').length) {//hooray!!! it exists...}\r\n\r\n**46. 使用jQuery判断鼠标的左右键点击**\r\n\r\n    $(\"#someelement\").live('click', function(e) {\r\n        if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {\r\n            alert(\"Left Mouse Button Clicked\");\r\n        }\r\n        else if(e.button == 2)\r\n            alert(\"Right Mouse Button Clicked\");\r\n    });\r\n\r\n \r\n\r\n**47. 显示或者删除输入框的缺省值**\r\n\r\n    //This snippet will show you how to keep a default value\r\n    //in a text input field for when a user hasn't entered in\r\n    //a value to replace it\r\n    swap_val = [];\r\n    $(\".swap\").each(function(i){\r\n        swap_val[i] = $(this).val();\r\n        $(this).focusin(function(){\r\n            if ($(this).val() == swap_val[i]) {\r\n                $(this).val(\"\");\r\n            }\r\n        }).focusout(function(){\r\n            if ($.trim($(this).val()) == \"\") {\r\n                $(this).val(swap_val[i]);\r\n            }\r\n        });\r\n    });\r\n    <INPUT class=swap value=\"Enter Username here..\" type=text> \r\n\r\n**48. 指定时间后自动隐藏或者关闭元素(1.4支持）**\r\n\r\n    //Here's how we used to do it in 1.3.2 using setTimeout\r\n    setTimeout(function() {\r\n      $('.mydiv').hide('blind', {}, 500)\r\n    }, 5000);\r\n    //And here's how you can do it with 1.4 using the delay() feature (this is a lot like sleep)\r\n    $(\".mydiv\").delay(5000).hide('blind', {}, 500);\r\n\r\n**49. 动态创建元素到DOM**\r\n\r\n    var newgbin1Div = $('');\r\n    newgbin1Div.attr('id','gbin1.com').appendTo('body');\r\n\r\n**50. 限制textarea的字符数量**\r\n\r\n    jQuery.fn.maxLength = function(max){\r\n      this.each(function(){\r\n        var type = this.tagName.toLowerCase();\r\n        var inputType = this.type? this.type.toLowerCase() : null;\r\n        if(type == \"input\" && inputType == \"text\" || inputType == \"password\"){\r\n          //Apply the standard maxLength\r\n          this.maxLength = max;\r\n        }\r\n        else if(type == \"textarea\"){\r\n          this.onkeypress = function(e){\r\n            var ob = e || event;\r\n            var keyCode = ob.keyCode;\r\n            var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;\r\n            return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);\r\n          };\r\n          this.onkeyup = function(){\r\n            if(this.value.length > max){\r\n              this.value = this.value.substring(0,max);\r\n            }\r\n          };\r\n        }\r\n      });\r\n    };\r\n    //Usage:\r\n    $('#gbin1textarea').maxLength(500);\r\n\r\n**51. 为函数创建一个基本测试用例**\r\n\r\n    //Separate tests into modules.\r\n    module(\"Module B\");\r\n    test(\"some other gbin1.com test\", function() {\r\n      //Specify how many assertions are expected to run within a test.\r\n      expect(2);\r\n      //A comparison assertion, equivalent to JUnit's assertEquals.\r\n      equals( true, false, \"failing test\" );\r\n      equals( true, true, \"passing test\" );\r\n    });\r\n\r\n**52. 使用jQuery克隆元素**\r\n\r\n    var cloned = $('#gbin1div').clone();\r\n\r\n**53. 测试一个元素在jQuery中是否可见**\r\n\r\n    if($(element).is(':visible') == 'true') { //The element is Visible }\r\n\r\n**54. 元素屏幕居中**\r\n\r\n    jQuery.fn.center = function () {\r\n      this.css('position','absolute');\r\n      this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 'px');\r\n      this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');return this;\r\n    }\r\n    //Use the above function as: $('#gbin1div').center();\r\n\r\n**55. 使用特定名字的元素对应的值生成一个数组**\r\n\r\n    var arrInputValues = new Array();\r\n    $(\"input[name='table[]']\").each(function(){\r\n         arrInputValues.push($(this).val());\r\n    });\r\n\r\n**56. 剔除元素中的HTML**\r\n\r\n    (function($) {\r\n        $.fn.stripHtml = function() {\r\n            var regexp = /<(\"[^\"]*\"|'[^']*'|[^'\">])*>/gi;\r\n            this.each(function() {\r\n                $(this).html(\r\n                    $(this).html().replace(regexp,\"\")\r\n                );\r\n            });\r\n            return $(this);\r\n        }\r\n    })(jQuery);\r\n    //usage:\r\n    $('p').stripHtml();\r\n\r\n**57. 使用closest来得到父元素**\r\n\r\n    $('#searchBox').closest('div');\r\n\r\n**58. 使用firebug来记录jQuery事件**\r\n\r\n    // Allows chainable logging\r\n    // Usage: $('#someDiv').hide().log('div hidden').addClass('someClass');\r\n    jQuery.log = jQuery.fn.log = function (msg) {\r\n          if (console){\r\n             console.log(\"%s: %o\", msg, this);\r\n          }\r\n          return this;\r\n    };\r\n\r\n\r\n**59. 点击链接强制弹出新窗口**\r\n\r\n    jQuery('a.popup').live('click', function(){\r\n      newwindow=window.open($(this).attr('href'),'','height=200,width=150');\r\n      if (window.focus) {newwindow.focus()}\r\n      return false;\r\n    });\r\n\r\n**60 .点击链接强制打开新标签页**\r\n\r\n    jQuery('a.newTab').live('click', function(){\r\n      newwindow=window.open($(this).href);\r\n      jQuery(this).target = \"_blank\";\r\n      return false;\r\n    });\r\n\r\n**61 .简单的tab标签切换**\r\n\r\n    jQuery('#meeting_tabs ul li').click(function(){\r\n            jQuery(this).addClass('tabulous_active').siblings().removeClass('tabulous_active');\r\n            jQuery('#tabs_container>.pane:eq('+jQuery(this).index()+')').show().siblings().hide();   \r\n     })\r\n\r\n    <div id=\"meeting_tabs\">\r\n                    <ul>\r\n                         <li class=\"tabulous_active\"><a href=\"#\" title=\"\">进行中</a></li>\r\n                          <li><a href=\"#\" title=\"\">未开始</a></li>\r\n                          <li><a href=\"#\" title=\"\">已结束</a></li>\r\n                           <li><a href=\"#\" title=\"\">全部</a></li>\r\n                     </ul>\r\n       <div id=\"tabs_container\">\r\n                <div  class=\"pane\"     >1</div>\r\n                <div  class=\"pane\"     >2</div>\r\n                <div  class=\"pane\"     >3</div>\r\n               <div  class=\"pane\"     >4</div>\r\n      </div>\r\n    </div>\r\n\r\n是不是很简洁呢？"}}