龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > Javascript编程 >

50个必备的实用jQuery代码段(1)(4)

时间:2013-03-06 14:58来源:未知 作者:admin 点击:
分享到:
31. 如何在jQuery中克隆一个元素: var cloned=$( '#somediv' ).clone(); 32. 在jQuery中如何测试某个元素是否可见 if ($(element).is( ':visible' )== 'true' ){ //该元素是可见的

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

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

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

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

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

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

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

35. 如何从元素中除去HTML

  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(); 

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

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

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

  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. }; 

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

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

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

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

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

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

精彩图集

赞助商链接