【经典源码收藏】jQuery实用代码片段(筛选,搜索,样式,清除默认值

2020-05-29 07:17:41易采站长站整理


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

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


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

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;
}
//这样来使用上面的函数:
$(element).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);
//用法:
$('p').stripHtml();

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


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

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


// 允许链式日志记录
// 用法:
$('#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. 在jQuery中如何使用.siblings()来选择同辈元素


// 不这样做
$('#nav li').click(function () {
$('#nav li').removeClass('active');
$(this).addClass('active');
});
//替代做法是
$('#nav li').click(function () {
$(this).addClass('active').siblings().removeClass('active');
});