常用的经典jquery代码[转]

0. 如何创建嵌套的过滤器:

[javascript]view plaincopy

  1. //允许你减少集合中的匹配元素的过滤器,
  2. //只剩下那些与给定的选择器匹配的部分。在这种情况下,
  3. //查询删除了任何没(:not)有(:has)
  4. //包含class为“selected”(.selected)的子节点。
  5. .filter(":not(:has(.selected))")

1.任何使用has()来检查某个元素是否包含某个类或是元素:

[javascript]view plaincopy

  1. //jQuery 1.4.*包含了对这一has方法的支持。该方法找出
  2. //某个元素是否包含了其他另一个元素类或是其他任何的
  3. //你正在查找并要在其之上进行操作的东东。
  4. $("input").has(".email").addClass("email_icon");

2. 如何使用jQuery来切换样式表

[javascript]view plaincopy

  1. //找出你希望切换的媒体类型(media-type),然后把href设置成新的样式表。
  2. $('link[media='screen']').attr('href', 'Alternative.css');

3. 如何限制选择范围(基于优化目的):

[javascript]view plaincopy

  1. //尽可能使用标签名来作为类名的前缀,
  2. //这样jQuery就不需要花费更多的时间来搜索
  3. //你想要的元素。还要记住的一点是,
  4. //针对于你的页面上的元素的操作越具体化,
  5. //就越能降低执行和搜索的时间。
  6. var in_stock = $('#shopping_cart_items input.is_in_stock');
  7. <ul >
  8. <li><input type="radio" value="Item-X" name="item" class="is_in_stock" /> Item X</li>
  9. <li><input type="radio" value="Item-Y" name="item" class="3-5_days" /> Item Y</li>
  10. <li><input type="radio" value="Item-Z" name="item" class="unknown" /> Item Z</li>
  11. </ul>

4. 如何正确地使用ToggleClass:

[javascript]view plaincopy

  1. //切换(toggle)类允许你根据某个类的
  2. //是否存在来添加或是删除该类。
  3. //这种情况下有些开发者使用:
  4. a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton');
  5. //toggleClass允许你使用下面的语句来很容易地做到这一点
  6. a.toggleClass('blueButton');

5如何设置IE特有的功能:

[javascript]view plaincopy

  1. if ($.browser.msie) {
  2. // Internet Explorer就是个虐待狂
  3. }

7. 如何使用jQuery来代替一个元素:

[javascript]view plaincopy

  1. $('#thatdiv').replaceWith('fnuh');

8. 如何验证某个元素是否为空:

[javascript]view plaincopy

  1. if ($('#keks').html() == null) {
  2. //什么都没有找到;
  3. }

9. 如何从一个未排序的集合中找出某个元素的索引号

[javascript]view plaincopy

  1. $("ul > li").click(function () {
  2. var index = $(this).prevAll().length;
  3. });

10. 如何把函数绑定到事件上:

[javascript]view plaincopy

  1. $('#foo').bind('click', function() {
  2. alert('User clicked on "foo."');
  3. });

11. 如何追加或是添加html到元素中:

[javascript]view plaincopy

  1. $('#lal').append('sometext');

12. 在创建元素时,如何使用对象字面量(literal)来定义属性

[javascript]view plaincopy

  1. var e = $("", { href: "#", class: "a-class another-class", title: "..." });

13. 如何使用多个属性来进行过滤

[javascript]view plaincopy

  1. //在使用许多相类似的有着不同类型的input元素时,
  2. //这种基于精确度的方法很有用
  3. var elements = $('#someid input[type=sometype][value=somevalue]').get();

14. 如何使用jQuery来预加载图像:

[javascript]view plaincopy

  1. jQuery.preloadImages = function() {
  2. for(var i = 0; i < arguments.length; i++) {
  3. $("<img />").attr('src', arguments[i]);
  4. }
  5. };
  6. //用法
  7. $.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg');

15. 如何为任何与选择器相匹配的元素设置事件处理程序:

[javascript]view plaincopy

  1. $('button.someClass').live('click', someFunction);
  2. //注意,在jQuery 1.4.2中,delegate和undelegate选项
  3. //被引入代替live,因为它们提供了更好的上下文支持
  4. //例如,就table来说,以前你会用
  5. //.live()
  6. $("table").each(function(){
  7. $("td", this).live("hover", function(){
  8. $(this).toggleClass("hover");
  9. });
  10. });
  11. //现在用
  12. $("table").delegate("td", "hover", function(){
  13. $(this).toggleClass("hover");
  14. });

16. 如何找到一个已经被选中的option元素:

[javascript]view plaincopy

  1. $('#someElement').find('option:selected');

17. 如何隐藏一个包含了某个值文本的元素:

[javascript]view plaincopy

  1. $("p.value:contains('thetextvalue')").hide();

18. 如何自动滚动到页面中的某区域

[javascript]view plaincopy

  1. jQuery.fn.autoscroll = function(selector) {
  2. $('html,body').animate(
  3. {scrollTop: $(selector).offset().top},
  4. 500
  5. };
  6. }
  7. //然后像这样来滚动到你希望去到的class/area上。
  8. $('.area_name').autoscroll();

19. 如何检测各种浏览器

[javascript]view plaincopy

  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' ))

20. 如何替换串中的词

[javascript]view plaincopy

  1. var el = $('#id');
  2. el.html(el.html().replace(/word/ig, ''));

21. 如何禁用右键单击上下文菜单:

[javascript]view plaincopy

  1. $(document).bind('contextmenu',function(e){
  2. return false;
  3. });

22. 如何定义一个定制的选择器

[javascript]view plaincopy

  1. $.expr[':'].mycustomselector = function(element, index, meta, stack){
  2. // element- 一个DOM元素
  3. // index – 栈中的当前循环索引
  4. // meta – 有关选择器的元数据
  5. // stack – 要循环的所有元素的栈
  6. // 如果包含了当前元素就返回true
  7. // 如果不包含当前元素就返回false };
  8. // 定制选择器的用法:
  9. $('.someClasses:test').doSomething();

23. 如何检查某个元素是否存在

[javascript]view plaincopy

  1. if ($('#someDiv').length) {
  2. //万岁!!!它存在……
  3. }

24. 如何使用jQuery来检测右键和左键的鼠标单击两种情况:

[javascript]view plaincopy

  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");
  6. }
  7. });

25. 如何显示或是删除input域中的默认值

[html]view plaincopy

  1. <input type="text" value="Enter Username here.." class="swap" />

[javascript]view plaincopy

  1. wap_val = [];
  2. $(".swap").each(function(i){
  3. wap_val[i] = $(this).val();
  4. $(this).focusin(function(){
  5. if ($(this).val() == swap_val[i]) {
  6. $(this).val("");
  7. }
  8. }).focusout(function(){
  9. if ($.trim($(this).val()) == "") {
  10. $(this).val(swap_val[i]);
  11. }
  12. });
  13. });

26. 如何在一段时间之后自动隐藏或关闭元素(支持1.4版本):

[javascript]view plaincopy

  1. //这是1.3.2中我们使用setTimeout来实现的方式
  2. setTimeout(function() {
  3. $('.mydiv').hide('blind', {}, 500)
  4. }, 5000);
  5. //而这是在1.4中可以使用delay()这一功能来实现的方式(这很像是休眠)
  6. $(".mydiv").delay(5000).hide('blind', {}, 500);

27. 如何把已创建的元素动态地添加到DOM中:

[javascript]view plaincopy

  1. var newDiv = $('');
  2. newDiv.attr('id','myNewDiv').appendTo('body');

28. 如何限制“Text-Area”域中的字符的个数:

[javascript]view plaincopy

  1. jQuery.fn.maxLength = function(max){
  2. this.each(function(){
  3. var type = this.tagName.toLowerCase();
  4. var inputType = this.type? this.type.toLowerCase() : null;
  5. if(type == "input" && inputType == "text" || inputType == "password"){
  6. //Apply the standard maxLength
  7. this.maxLength = max;
  8. }
  9. else if(type == "textarea"){
  10. this.onkeypress = function(e){
  11. var ob = e || event;
  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);
  15. };
  16. this.onkeyup = function(){
  17. if(this.value.length > max){
  18. this.value = this.value.substring(0,max);
  19. }
  20. };
  21. }
  22. });
  23. };
  24. //用法
  25. $('#mytextarea').maxLength(500);

29. 如何为函数创建一个基本的测试

[javascript]view plaincopy

  1. //把测试单独放在模块中
  2. module("Module B");
  3. test("some other test", function() {
  4. //指明测试内部预期有多少要运行的断言
  5. expect(2);
  6. //一个比较断言,相当于JUnit的assertEquals
  7. equals( true, false, "failing test" );
  8. equals( true, true, "passing test" );
  9. });

30. 如何在jQuery中克隆一个元素:

[javascript]view plaincopy

  1. var cloned = $('#somediv').clone();

31. 在jQuery中如何测试某个元素是否可见

[javascript]view plaincopy

  1. if($(element).is(':visible') == 'true') {
  2. //该元素是可见的
  3. }

32. 如何把一个元素放在屏幕的中心位置:

[javascript]view plaincopy

  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');
  5. return this;
  6. }
  7. //这样来使用上面的函数:
  8. $(element).center();

33. 如何把有着某个特定名称的所有元素的值都放到一个数组中:

[javascript]view plaincopy

  1. var arrInputValues = new Array();
  2. $("input[name='table[]']").each(function(){
  3. arrInputValues.push($(this).val());
  4. });

34. 如何从元素中除去html

[javascript]view plaincopy

  1. (function($) {
  2. $.fn.stripHtml = function() {
  3. var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
  4. this.each(function() {
  5. $(this).html( $(this).html().replace(regexp,”") );
  6. });
  7. return $(this);
  8. }
  9. })(jQuery);
  10. //用法:
  11. $('p').stripHtml();

35. 如何使用closest来取得父元素:

[javascript]view plaincopy

  1. $('#searchBox').closest('div');

36. 如何使用Firebug和Firefox来记录jQuery事件日志:

[javascript]view plaincopy

  1. // 允许链式日志记录
  2. // 用法:
  3. $('#someDiv').hide().log('div hidden').addClass('someClass');
  4. jQuery.log = jQuery.fn.log = function (msg) {
  5. if (console){
  6. console.log("%s: %o", msg, this);
  7. }
  8. return this;
  9. };

37. 如何强制在弹出窗口中打开链接:

[javascript]view plaincopy

  1. jQuery('a.popup').live('click', function(){
  2. newwindow=window.open($(this).attr('href'),'','height=200,width=150');
  3. if (window.focus) {
  4. newwindow.focus();
  5. }
  6. return false;
  7. });

38. 如何强制在新的选项卡中打开链接:

[javascript]view plaincopy

  1. jQuery('a.newTab').live('click', function(){
  2. newwindow=window.open($(this).href);
  3. jQuery(this).target = "_blank";
  4. return false;
  5. });

39. 在jQuery中如何使用.siblings()来选择同辈元素

[javascript]view plaincopy

  1. // 不这样做
  2. $('#nav li').click(function(){
  3. $('#nav li').removeClass('active');
  4. $(this).addClass('active');
  5. });
  6. //替代做法是
  7. $('#nav li').click(function(){
  8. $(this).addClass('active').siblings().removeClass('active');
  9. });

40. 如何切换页面上的所有复选框:

[javascript]view plaincopy

  1. var tog = false;
  2. // 或者为true,如果它们在加载时为被选中状态的话
  3. $('a').click(function() {
  4. $("input[type=checkbox]").attr("checked",!tog);
  5. tog = !tog;
  6. });

41. 如何基于一些输入文本来过滤一个元素列表:

[javascript]view plaincopy

  1. //如果元素的值和输入的文本相匹配的话
  2. //该元素将被返回
  3. $('.someClass').filter(function() {
  4. return $(this).attr('value') == $('input#someId').val();
  5. })

42. 如何获得鼠标垫光标位置x和y

[javascript]view plaincopy

  1. $(document).ready(function() {
  2. $(document).mousemove(function(e){
  3. $(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);
  4. });
  5. });

43. 如何把整个的列表元素(List Element,LI)变成可点击的

[html]view plaincopy

  1. <ul>
  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>
  6. </ul>

[javascript]view plaincopy

  1. $("ul li").click(function(){
  2. window.location=$(this).find("a").attr("href");
  3. return false;
  4. });

44. 如何使用jQuery来解析XML(基本的例子):

[javascript]view plaincopy

  1. function parseXml(xml) {
  2. //找到每个Tutorial并打印出author
  3. $(xml).find("Tutorial").each(function() {
  4. $("#output").append($(this).attr("author") + "");
  5. });
  6. }

45. 如何检查图像是否已经被完全加载进来

[javascript]view plaincopy

  1. $('#theImage').attr('src', 'image.jpg').load(function() {
  2. alert('This Image Has Been Loaded');
  3. });

46. 如何使用jQuery来为事件指定命名空间:

[javascript]view plaincopy

  1. //事件可以这样绑定命名空间
  2. $('input').bind('blur.validation', function(e){
  3. // ...
  4. });
  5. //data方法也接受命名空间
  6. $('input').data('validation.isValid', true);

47. 如何检查cookie是否启用

[javascript]view plaincopy

  1. var dt = new Date();
  2. dt.setSeconds(dt.getSeconds() + 60);
  3. document.cookie = "cookietest=1; expires=" + dt.toGMTString();
  4. var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
  5. if(!cookiesEnabled) {
  6. //没有启用cookie
  7. }

48. 如何让cookie过期:

[javascript]view plaincopy

  1. var date = new Date();
  2. date.setTime(date.getTime() + (x * 60 * 1000));
  3. $.cookie('example', 'foo', { expires: date });

49. 如何使用一个可点击的链接来替换页面中任何的URL

[javascript]view plaincopy

  1. $.fn.replaceUrl = function() {
  2. var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
  3. this.each(function() {
  4. $(this).html(
  5. $(this).html().replace(regexp,'<a href="$1">$1</a>‘)
  6. );
  7. });
  8. return $(this);
  9. }
  10. //用法 
  11. $('p').replaceUrl();