jquery备忘

来源:互联网 发布:linux iconv命令 编辑:程序博客网 时间:2024/04/30 07:03

1。讲元素添加到数组中

var arrInputValues = new Array();  

$("input[name='table[]']").each(function(){  

    arrInputValues.push($(this).val());  

}); 

2.在jQuery中如何使用.siblings()来选择同辈元素

// 不这样做  

$('#nav li').click(function(){  

    $('#nav li').removeClass('active');  

    $(this).addClass('active');  

});  

//替代做法是  

$('#nav li').click(function(){  

    $(this).addClass('active').siblings().removeClass('active');  

}); 

3如何获得鼠标垫光标位置x和y

$(document).ready(function() {  

    $(document).mousemove(function(e){  

       $(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);  

    });  

}); 

 

4如何使用jQuery来解析XML(基本的例子):

function parseXml(xml) {  

    //找到每个Tutorial并打印出author  

    $(xml).find("Tutorial").each(function() {  

       $("#output").append($(this).attr("author") + "");  

    });  

5如何检查图像是否已经被完全加载进来

$('#theImage').attr('src''image.jpg').load(function() {  

   alert('This Image Has Been Loaded');  

}); 

6. 如何使用jQuery来为事件指定命名空间://事件可以这样绑定命名空间  

$('input').bind('blur.validation'function(e){  

// ...  

});  

//data方法也接受命名空间  

$('input').data('validation.isValid'true); 

7 如何检查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) {  

//没有启用cookie  

8. 如何让cookie过期:

var date = new Date();  

date.setTime(date.getTime() + (x * 60 * 1000));  

$.cookie('example''foo', { expires: date }); 

9. 如何使用一个可点击的链接来替换页面中任何的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);  

}  

//用法   

$('p').replaceUrl(); 

 10.

10、支持方法的连写
所谓连写,即可以对一个jquery对象连续调用各种不同的方法。
例如:
$("p").click(function(){alert($(this).html())})
.mouseover(function(){alert('mouse over event')})
.each(function(i){this.style.color=['#f00','#0f0','#00f'][i]});