jQuery.fn.maxLength = function(max){
this.each(function(){ 1
var type = this.tagName.toLowerCase(); 2
var inputType = this.type? this.type.toLowerCase() : null; 3
if(type == \ && inputType == \ || inputType == \ 4
//Apply the standard maxLength 5
this.maxLength = max; 6 } 7
else if(type == \ 8
this.onkeypress = function(e){ 9
var ob = e || event; 10
var keyCode = ob.keyCode; 11 var hasSelection = document.selection? 12
document.selection.createRange().text.length > 0 : this.selectionStart != 13
this.selectionEnd; 14
return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 15
|| keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection); 16 }; 17
this.onkeyup = function(){ 18
if(this.value.length > max){ 19
this.value = this.value.substring(0,max); 20 } 21 }; 22 } 23 }); 24 }; 25
//用法
$('#mytextarea').maxLength(500);
30. 如何为函数创建一个基本的测试 ? //把测试单独放在模块中 1 module(\ 2
test(\ 3
//指明测试内部预期有多少要运行的断言 4
expect(2); 5
//一个比较断言,相当于JUnit的assertEquals 6
equals( true, false, \ ); 7
equals( true, true, \ ); 8 9});
31. 如何在jQuery中克隆一个元素: ? var cloned = $('#somediv').clone(); 1 32. 在jQuery中如何测试某个元素是否可见 ? if($(element).is(':visible') == 'true') { 1 //该元素是可见的 2 3}
33. 如何把一个元素放在屏幕的中心位置: ? jQuery.fn.center = function () { this.css('position','absolute'); 1
this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 2
'px'); 3
this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 4
'px'); 5
return this; 6 } 7 8// 这样来使用上面的函数: $(element).center();
34. 如何把有着某个特定名称的所有元素的值都放到一个数组中: ? var arrInputValues = new Array(); 1
$(\ 2
arrInputValues.push($(this).val()); 3 4});
35. 如何从元素中除去html ? 1 (function($) {
2 $.fn.stripHtml = function() {
3 var regexp = /<(\ 4 this.each(function() {
5 $(this).html( $(this).html().replace(regexp,”\ 6 });
7 return $(this); 8 }
9 })(jQuery); //用法: 10
$('p').stripHtml(); 11
36. 如何使用closest来取得父元素: ? $('#searchBox').closest('div'); 1 37. 如何使用Firebug和Firefox来记录jQuery事件日志: ? // 允许链式日志记录 1 // 用法: 2
$('#someDiv').hide().log('div hidden').addClass('someClass'); 3
jQuery.log = jQuery.fn.log = function (msg) { 4
if (console){ 5
console.log(\ 6 } 7
return this; 8 9};
38. 如何强制在弹出窗口中打开链接: ? jQuery('a.popup').live('click', function(){ 1
newwindow=window.open($(this).attr('href'),'','height=200,width=150'); 2
if (window.focus) { 3
newwindow.focus(); 4 } 5
return false; 6
7});
39. 如何强制在新的选项卡中打开链接: ? jQuery('a.newTab').live('click', function(){ 1
newwindow=window.open($(this).href); 2
jQuery(this).target = \ 3
return false; 4 5});
40. 在jQuery中如何使用.siblings()来选择同辈元素 ? // 不这样做 1
$('#nav li').click(function(){ 2
$('#nav li').removeClass('active'); 3
$(this).addClass('active'); 4 }); 5
//替代做法是 6
$('#nav li').click(function(){ 7
$(this).addClass('active').siblings().removeClass('active'); 8 9});
41. 如何切换页面上的所有复选框: ?

