web前端开发JQuery常用实例代码片段(50个)

2020-05-29 07:12:58易采站长站整理


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

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


var newDiv = $(”);
newDiv.attr(‘id', ‘myNewDiv').appendTo(‘body');

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


jQuery.fn.maxLength = function (max) { this.each(function () { var type = this.tagName.toLowerCase(); var inputType = this.type ? this.type.toLowerCase() : null; if (type == "input" && inputType == "text" || inputType == "password") { this.maxLength = max; } else if (type == "textarea") { this.onkeypress = function (e) { var ob = e || event; var keyCode = ob.keyCode; var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd; return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection); }; this.onkeyup = function () { if (this.value.length > max) { this.value = this.value.substring(0, max); } }; } }); };
//用法 $(‘#mytextarea').maxLength(500);

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


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

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


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

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


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

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