转自
http://www.gbin1.com/technology/jquery/50jquerycodesnippetsforbetterjavascript2/index.html
26. 显示或者删除输入框的缺省值
//This snippet will show you how to keep a default value
//in a text input field for when a user hasn't entered in
//a value to replace it
swap_val = [];
$(".swap").each(function(i){
swap_val[i] = $(this).val();
$(this).focusin(function(){
if ($(this).val() == swap_val[i]) {
$(this).val("");
}
}).focusout(function(){
if ($.trim($(this).val()) == "") {
$(this).val(swap_val[i]);
}
});
});
<INPUT class=swap value="Enter Username here.." type=text>
27. 指定时间后自动隐藏或者关闭元素(1.4支持)
//Here's how we used to do it in 1.3.2 using setTimeout
setTimeout(function() {
$('.mydiv').hide('blind', {}, 500)
}, 5000);
//And here's how you can do it with 1.4 using the delay() feature (this is a lot like sleep)
$(".mydiv").delay(5000).hide('blind', {}, 500);
28. 动态创建元素到DOM
var newgbin1Div = $('');
newgbin1Div.attr('id','gbin1.com').appendTo('body');
29. 限制textarea的字符数量
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"){
//Apply the standard maxLength
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);
}
};
}
});
};
//Usage:
$('#gbin1textarea').maxLength(500);
30. 为函数创建一个基本测试用例
//Separate tests into modules.
module("Module B");
test("some other gbin1.com test", function() {
//Specify how many assertions are expected to run within a test.
expect(2);
//A comparison assertion, equivalent to JUnit's assertEquals.
equals( true, false, "failing test" );
equals( true, true, "passing test" );
});
31. 使用jQuery克隆元素
var cloned = $('#gbin1div').clone();
32. 测试一个元素在jQuery中是否可见
if($(element).is(':visible') == 'true') { //The 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;
}
//Use the above function as: $('#gbin1div').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);
//usage:
$('p').stripHtml();
36. 使用closest来得到父元素
$('#searchBox').closest('div');
37. 使用firebug来记录jQuery事件
// Allows chainable logging
// Usage: $('#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. 使用siblings()来处理同类元素
// Rather than doing this
$('#nav li').click(function(){
$('#nav li').removeClass('active');
$(this).addClass('active');
});
// Do this instead
$('#nav li').click(function(){
$(this).addClass('active')
.siblings().removeClass('active');
});
41. 选择或者不选页面上全部复选框
var tog = false; // or true if they are checked on load
$('a').click(function() {
$("input[type=checkbox]").attr("checked",!tog);
tog = !tog;
});
42. 基于输入文字过滤页面元素
//If the value of the element matches that of the entered text
//it will be returned
$('.gbin1Class').filter(function() {
return $(this).attr('value') == $('input#gbin1Id').val() ;
})
43. 取得鼠标的X和Y坐标
$(document).mousemove(function(e){
$(document).ready(function() {
$().mousemove(function(e){
$('#XY').html("Gbin1 X Axis : " + e.pageX + " | Gbin1 Y Axis " + e.pageY);
});
});
44. 使得整个列表元素(LI)可点击
$("ul li").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
<UL>
<LI><A href="#">GBin1 Link 1</A></LI>
<LI><A href="#">GBin1 Link 2</A></LI>
<LI><A href="#">GBin1 Link 3</A></LI>
<LI><A href="#">GBin1 Link 4</A></LI>
</UL>
45. 使用jQuery来解析XML
function parseXml(xml) {
//find every Tutorial and print the author
$(xml).find("Tutorial").each(function()
{
$("#output").append($(this).attr("author") + "");
});
}
46. 判断一个图片是否加载完全
$('#theGBin1Image').attr('src', 'image.jpg').load(function() {
alert('This Image Has Been Loaded');
});
47. 使用jQuery命名事件
//Events can be namespaced like this
$('input').bind('blur.validation', function(e){
// ...
});
//The data method also accept namespaces
$('input').data('validation.isValid', true);
48. 判断cookie是否激活或者关闭
var dt = new Date();
dt.setSeconds(dt.getSeconds() + 60);
document.cookie = "cookietest=1; expires=" + dt.toGMTString();
var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
if(!cookiesEnabled)
{
//cookies have not been enabled
}
49. 强制过期cookie
var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });
50. 使用一个可点击的链接替换页面中所有URL
$.fn.replaceUrl = function() {
var regexp = /((ftp|http|https)://(w+:{0,1}w*@)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%@!-/]))?)/gi;
this.each(function() {
$(this).html(
$(this).html().replace(regexp,'<A href="$1">$1</A>')
);
});
return $(this);
}
//usage
$('#GBin1div').replaceUrl();
原文出处:
分享50个使你成为高级javascript开发者的jQuery的代码开发技巧 - 第一部分
分享50个使你成为高级javascript开发者的jQuery的代码开发技巧 - 第二部分
分享到:
相关推荐
本资源的“精通JavaScript+jQuery电子书”的第二部分可能涵盖了这两个领域的高级主题,如闭包、模块化开发、jQuery插件开发、异步编程的最佳实践、性能优化策略等。结合提供的源码,学习者可以深入理解理论知识并...
JavaScript是一种广泛应用于网页和...通过阅读“精通JavaScript+jQuery电子书”的第五部分并结合提供的源码,读者不仅可以巩固理论知识,还能提高解决实际问题的能力,为成为JavaScript和jQuery的大师打下坚实基础。
JavaScript和jQuery是Web开发中的两个重要工具,它们极大地简化了网页动态化和交互性设计。JavaScript是一种轻量级的解释型编程语言,广泛应用于浏览器端,用于处理用户输入、操作DOM(文档对象模型)、实现页面动画...
在本教程中,我们将深入探讨Web前端开发的基础知识,涵盖了HTML、CSS、JavaScript以及jQuery这四个核心技术。这些技术是构建交互式、响应式的现代网页所必不可少的。 **HTML(超文本标记语言)** HTML是网页内容的...
这个名为"JavaScript前端开发案例教程-源代码.rar"的压缩包文件提供了一系列实践案例,帮助开发者深入理解和掌握JavaScript在网页开发中的应用。 首先,JavaScript是一种解释型、弱类型、基于原型的脚本语言,它的...
总的来说,《jQuery移动Web开发(第二版)》的源代码提供了丰富的实践材料,涵盖了从基础概念到高级技巧的全面内容。无论是初学者还是经验丰富的开发者,都能从中受益,提升在移动Web领域的开发能力。通过深入研究和...
标题 "我的第一个jquery封装方法---jquery" 暗示了这篇博客主要关注的是如何使用jQuery这一流行的JavaScript库来封装自定义的功能。jQuery以其简洁的API和强大的DOM操作能力,成为了前端开发者的常用工具。在这里,...
内容全面、丰富、翔实,不仅由浅入深地讲解了jQuery的所有必备基础知识,还介绍了jQuery UI等扩展知识以及jQuery开发中的技巧与性能优化方面的高级知识。 本书极其注重实战,因为动手实践才是掌握一门新技术的最...
在"jQ学习第一季"、"jQ学习第二季"、"jQ学习第三季"的文件中,你可以找到更具体和丰富的实例,涵盖更多高级技巧和最佳实践。通过实践这些实例,你将能够更加熟练地运用jQuery来实现网页的各种动态效果和交互功能,...
Web编程基础涵盖了许多关键概念,特别是CSS、JavaScript和jQuery,这些都是构建现代网页不可或缺的组成部分。在Web标准中,我们首先需要理解的是Web标准的核心意义及其重要性。Web标准旨在规范网页设计,确保不同...
《jQuery基础教程(第2版)》是一本深入浅出介绍jQuery库的书籍,其源代码包含了一系列示例和练习,旨在帮助读者更好地理解和掌握jQuery的核心功能和实用技巧。jQuery是一个广泛使用的JavaScript库,它极大地简化了...
在本压缩包中,我们关注的是"javascript+jquery书的例子源码第2章",这表明内容主要涉及JavaScript和jQuery的结合使用,特别是第二章的相关示例代码。JavaScript是一种广泛用于网页和网络应用的编程语言,而jQuery...
在"JS/JQuery-第7章上机练习.zip"这个压缩包中,我们可以推测这是一份关于JavaScript和JQuery实践训练的资料,尤其聚焦于第七章的内容。通常,这样的练习会帮助开发者巩固和提升在实际项目中的应用能力。 1. **选择...
【标题】"artech-javascript-jquery-11"揭示了这一主题主要关注的是JavaScript库jQuery的第11部分。jQuery是一个广泛使用的JavaScript库,它极大地简化了HTML文档遍历、事件处理、动画以及Ajax交互等任务。在这个...
学习《精通jQuery(中文第二版)》,不仅可以提升JavaScript编程技能,还能使开发者在网页动态效果和用户体验上有所突破,为Web应用开发注入更多活力。通过深入阅读和实践,读者将能够熟练运用jQuery,提升开发效率...
jQuery UI 是一个基于广泛使用的 JavaScript 库 jQuery 的扩展,它为开发者提供了丰富的用户界面组件和交互效果。这个名为 "jquery-ui-1.10.4.custom" 的压缩包文件,很显然是一个自定义版本的 jQuery UI,版本号为 ...
此外,还会涉及更高级的主题,如闭包、原型链和异步编程,这些都是成为熟练JavaScript开发者所必须掌握的。 jQuery是一个JavaScript库,它的目标是简化JavaScript的使用,使得操作DOM(文档对象模型)、处理事件、...
《使用简单代码实现jQuery特效的jquery-tutorials》 在网页开发中,jQuery库因其简洁的API和强大的功能而被广泛使用。这篇博文“不用插件简单代码实现JQuery特效的jquery-tutorials”提供了关于如何利用jQuery创建...
这些是JavaScript编程的基石,理解和熟练运用它们是成为一名优秀JavaScript开发者的关键。 2. 高级JavaScript特性:可能包括对象和原型、模块化、异步编程(如回调函数、Promise和async/await)、事件监听与处理、...
如果需要自定义文件名,可以在调用`wordExport`时传递第二个参数: ```javascript $(document).ready(function(){ $('#myDiv').wordExport('我的文档.docx'); }); ``` 这样,生成的Word文档将会以"我的文档.docx...