您的位置:首页 > Web前端 > JQuery

常用jquery代码片段

2013-07-04 10:20 489 查看
一、获取一串url中的各个参数的值

// 解析url 返回json数组
function readSearch() {
var search = window.location.search;//此为获取浏览器地址栏url,可根据实际需要改为自己的url
var s = new Object();
var searchArray = search.replace("?", "").split("&");
for ( var i = 0; i < searchArray.length; i++) {
var paraArray = searchArray[i].split("=");
var key = paraArray[0];
var value = paraArray[1];
s[key] = value;
}
return s;
}

二、对表单常用操作

代码片段1: 在表单中禁用“回车键”

大家可能在表单的操作中需要防止用户意外的提交表单,那么下面这段代码肯定非常有帮助:

$("#form").keypress(function(e) {
if (e.which == 13) {
return false;
}
});


代码片段2: 清除所有的表单数据

可能针对不同的表单形式,你需要调用不同类型的清楚方法,不过使用下面这个现成方法,绝对能让你省不少功夫。

function clearForm(form) {
// iterate over all of the inputs for the form
// element that was passed in
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};


代码片段3: 将表单中的按钮禁用

下面的代码对于ajax操作非常有用,你可以有效的避免用户多次提交数据,个人也经常使用:

禁用按钮:

$("#somebutton").attr("disabled", true);
启动按钮:

$("#submit-button").removeAttr("disabled");
可能大家往往会使用.attr(‘disabled’,false);,不过这是不正确的调用。

代码片段4: 输入内容后启用递交按钮

这个代码和上面类似,都属于帮助用户控制表单递交按钮。使用这段代码后,递交按钮只有在用户输入指定内容后才可以启动。

$('#username').keyup(function() {
$('#submit').attr('disabled', !$('#username').val());
});


代码片段5: 禁止多次递交表单

多次递交表单对于web应用来说是个比较头疼的问题,下面的代码能够很好的帮助你解决这个问题:

$(document).ready(function() {
$('form').submit(function() {
if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
jQuery.data(this, "disabledOnSubmit", { submited: true });
$('input[type=submit], input[type=button]', this).each(function() {
$(this).attr("disabled", "disabled");
});
return true;
}
else
{
return false;
}
});
});


代码片段6: 高亮显示目前聚焦的输入框标示

有时候你需要提示用户目前操作的输入框,你可以使用下面代码高亮显示标示:

$("form :input").focus(function() {
$("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
$("label").removeClass("labelfocus");
});


代码片段7: 动态方式添加表单元素

这个方法可以帮助你动态的添加表单中的元素,比如,input等:

//change event on password1 field to prompt new input
$('#password1').change(function() {
//dynamically create new input and insert after password1
$("#password1").append("<input type='text' name='password2' id='password2' />");
});


代码片段8: 自动将数据导入selectbox中

下面代码能够使用ajax数据自动生成选择框的内容

$(function(){
$("select#ctlJob").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("select#ctlPerson").html(options);
})
})
})


代码片段9: 判断一个复选框是否被选中

代码很简单,如下:

$('#checkBox').attr('checked');


代码片段10: 使用代码来递交表单

代码很简单,如下:

$("#myform").submit();

三、

1. 控制鼠标悬停

$("a").hover(
function () {
// code on hover over
},
function () {
// code on away from hover
}
);


示例

2. 载入的时候防止锚链接

$("a").on("click", function(e){
e.preventDefault();
});


示例
该方法将通知 Web 浏览器不要执行与事件关联的默认动作(如果存在这样的动作)这通常是用于触发某些类型的动态效果,如一个隐藏的菜单或Ajax调用。通过使用事件对象,我们可以操作数据发回给浏览器的URL。在这种情况下,停止HREF加载任何东西!

3. 滚动到顶部

$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});

示例
你可能已经看到这个功能的在新的社交网站越来越受欢迎

4. Ajax Template

$.ajax({
type: 'POST',
url: 'backend.php',
data: "q="+myform.serialize(),
success: function(data){
// on success use return data here
},
error: function(xhr, type, exception) {
// if ajax fails display error alert
alert("ajax error response type "+type);
}
});


示例
通过Ajax表单数据传递,是jQuery的最常见的用途之一。作为Web开发人员我们肯定记不住已经用过这个方法多少次了,语法非常简单,每次用到的时候都需要这段代码复制过去

5. 动画动作

1 $('p').animate({
2     left: '+=90px',
3     top: '+=150px',
4     opacity: 0.25
5   }, 900, 'linear', function() {
6     // function code on animation complete
7 });


示例
正如我们所看到的动画的方法,这是非常强大的,用于创建您的网页上的动画运动。

6. 切换CSS类

1 $('nav a').toggleClass('selected');


示例
添加或删除css类在html元素当中是一种相当普遍的动作. 这种技术经常运用在菜单切换,或者想用不用的颜色显示出某一行,或者页面的输入元素进行变化。 他经常结合addClass()和removeClass()方法来使用 你可以把所有的代码放到一个函数调用

7. 切换可见性

$("a.register").on("click", function(e){
$("#signup").fadeToggle(750, "linear");
});


示例
经常我们打开网址的时候。有的页面会弹出框或通知,需要几秒钟显示,然后隐藏。使用fadeToggle功能,您可以快速隐藏和显示任何DOM对象。

8. 载入外部内容

$("#content").load("somefile.html", function(response, status, xhr) {
// error handling
if(status == "error") {
$("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
}
});


示例
不需要使用ajax技术,就能够解析一个外部的html文件中的任何内容,这个新的内容可以加载到DOM在页面中的任何地方。非常的实用

9. 键盘事件

1 $('input').keydown(function(e) {
2   // variable e contains keystroke data
3   // only accessible with .keydown()
4   if(e.which == 11) {
5      e.preventDefault();
6   }
7 });
8
9 $('input').keyup(function(event) {
10   // run other event codes here
11 });


示例
处理用户输入是我们开发当中所遇到的比较头疼的难题。幸运的是jQuery的 keydown和keyup事件侦听是解决用户输入比较完美的解决方案。无论实用哪一张方法,你都要先确认用户将要产生的行为,再决定实用那个方法;

10.等高等宽

1 var maxheight = 0;
2 $("div.col").each(function(){
3   if($(this).height() > maxheight) { maxheight = $(this).height(); }
4 });
5
6 $("div.col").height(maxheight);


示例

11. 追加新的html

var sometext = "here is more HTML";
$("p#text1").append(sometext); // added after
$("p#text1").prepend(sometext); // added before


示例
使用
的append()
方法,我们可以快速地将任何HTML代码直接到DOM中。这跟前面提到的
load()方法
是类似的,

12. 设置和获取属性

1 var alink = $("a#user").attr("href"); // 获取链接的属性值
2 $("a#user").attr("href", "http://www.google.com/"); // 重新赋值
3 $("a#user").attr({
4   alt: "the classiest search engine",
5   href: "http://www.google.com/"
6 }); // set more than one attribute to new values


示例
此属性是相对简单的,但是如果处理不好经常会返回stackoverflow,
attr()
方法在任何HTML元素和属性的字符串值传递。结果是返回该属性值,所有的HTML属性可通过访问语法,所以是web开发当中必须要记住的

13. 检索内容值

1 $("p").click(function () {
2   var htmlstring = $(this).html(); // 获取html字符串
3   $(this).text(htmlstring); // 覆盖掉原来的html字符串
4 });
5
6 var value1 = $('input#username').val(); // 获取input的值
7 var value2 = $('input:checkbox:checked').val(); // 获取checkbox的值
8 var value3 = $('input:radio[name=bar]:checked').val(); // 获取button的值


示例
VAL()
属性是用来获取输入字段和表单元素的值

14. 遍历DOM

1 $("div#home").prev("div"); // find the div previous in relation to the current div
2 $("div#home").next("ul"); // find the next ul element after the current div
3 $("div#home").parent(); // returns the parent container element of the current div
4 $("div#home").children("p"); // returns only the paragraphs found inside the current div


原文链接:http://www.qianduan.net/10-awesome-jquery-form-action-code-fragment-not-to-be-missed.html

四、

1.平滑滚动到锚点

这个功能很常见,在网站底部添加一个让访客快速回到页面顶部的功能,下面是实现这个功能的示例代码:

// HTML:
// <h1 id="anchor">Lorem Ipsum</h1>
// <p><a href="#anchor" class="topLink">Back to Top</a></p>

$(document).ready(function() {
$("a.topLink").click(function() {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
}, {
duration: 500,
easing: "swing"
});
return false;
});
});

2.缩放图片

虽然图片应该在服务器端缩放,不过如果服务器端未做缩放,需要再客户端缩放的时候,可以使用下面这个方便的代码片段:

$(window).bind("load", function() {
// IMAGE RESIZE
$('#product_cat_list img').each(function() {
var maxWidth = 120;
var maxHeight = 120;
var ratio = 0;
var width = $(this).width();
var height = $(this).height();

if(width > maxWidth){
ratio = maxWidth / width;
$(this).css("width", maxWidth);
$(this).css("height", height * ratio);
height = height * ratio;
}
var width = $(this).width();
var height = $(this).height();
if(height > maxHeight){
ratio = maxHeight / height;
$(this).css("height", maxHeight);
$(this).css("width", width * ratio);
width = width * ratio;
}
});
//$("#contentpage img").show();
// IMAGE RESIZE
});


3.滚动时自动加载内容

很多网站使用了流行的瀑布图布局,这种类型的网站在页面滚动的时候会自动加载内容。下面这段代码让你能够把这个功能搬到你的网站上。

var loading = false;
$(window).scroll(function(){
if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
if(loading == false){
loading = true;
$('#loadingbar').css("display","block");
$.get("load.php?start="+$('#loaded_max').val(), function(loaded){
$('body').append(loaded);
$('#loaded_max').val(parseInt($('#loaded_max').val())+50);
$('#loadingbar').css("display","none");
loading = false;
});
}
}
});

$(document).ready(function() {
$('#loaded_max').val(50);
});


4.检测密码强度

在表单功能中,经常会有检测用户输入的密码强度的功能,下面这个代码片段使用正则表达式来检测密码是否足够安全,当然记得在服务端也进行表单验证。

$('#pass').keyup(function(e) {
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
$('#passstrength').html('More Characters');
} else if (strongRegex.test($(this).val())) {
$('#passstrength').className = 'ok';
$('#passstrength').html('Strong!');
} else if (mediumRegex.test($(this).val())) {
$('#passstrength').className = 'alert';
$('#passstrength').html('Medium!');
} else {
$('#passstrength').className = 'error';
$('#passstrength').html('Weak!');
}
return true;
});


5.均衡元素的高度

使用纯 CSS代码实现均衡元素的高度比较困难,而下面这段 jQuery 代码会根据最高的元素来均衡所有的 Div 元素。

var maxHeight = 0;

$("div").each(function(){
if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});

$("div").height(maxHeight);


6.修复 IE6 PNG 问题

至今,IE6 在国内仍然占据了大量的份额,因此在 Web 开发中仍然需要考虑 IE6 的兼容问题。比较常用的 IE6 PNG 图片问题,下面这段代码可以方便的修复。

$('.pngfix').each( function() {
$(this).attr('writing-mode', 'tb-rl');
$(this).css('background-image', 'none');
$(this).css( 'filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="path/to/image.png",sizingMethod="scale")');
});


7.解析 JSON 字符串

使用 jQuery 解析 JSON 数据并不复杂。下面是一个高效解析 JSON 数据并将其追加到您的网页的例子。

function parseJson(){
//Start by calling the json object, I will be using a
//file from my own site for the tutorial
//Then we declare a callback function to process the data
$.getJSON('hcj.json',getPosts);

//The process function, I am going to get the title,
//url and excerpt for 5 latest posts
function getPosts(data){
//Start a for loop with a limit of 5
for(var i = 0; i < 5; i++){
var strPost = '<h2>'
+ data.posts[i].title
+ '</h2>'
+ '<p>'
+ data.posts[i].excerpt
+ '</p>'
+ '<a href="'
+ data.posts[i].url
+ '" title="Read '
+ data.posts[i].title
+ '">Read ></a>';
//Append the body with the string
$('body').append(strPost);
}
}
}

//Fire off the function in your document ready
$(document).ready(function(){
parseJson();
});


8.隔行换色

这是一个很老的功能了,在大的列表或表格中,隔行颜色可以大大提高内容的可读性。下面的代码可以非常简单实现这个功能。

$('div:odd').css("background-color", "#F4F4F8");
$('div:even').css("background-color", "#EFF1F1");


9.预加载图片

你是否注意到 facebook 相册的图片加载速度特别快?那是因为在你看到这些图片之前已经预加载到你的浏览器缓存中了。下面是实现这个类似功能的代码示例:

var nextimage = "/images/some-image.jpg";
$(document).ready(function(){
window.setTimeout(function(){
var img = $("<img>").attr("src", nextimage).load(function(){
//all done
});
}, 100);
});


10.让整个 Div 可点击

这是实现链接的父 Div 也能够点击的简单方法,HTML 示例代码如下:

<div class="myBox">
blah blah blah.
<a href="http://google.com">link</a>
</div>
下面的 jQuery 代码让整个 Div 可点击:

$(".myBox").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
原文链接:/content/314422.html

四、

1.鼠标滑入滑出事件

$('p').hover(function(){
alert('mouseenter function is running !');
},function(){
alert('mouseleaver function is running !');
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: