栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

jquery实用代码片段集合

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

jquery实用代码片段集合

加载google的jquery库

有利于加快加载速度(已经得到验证)。

修改图片src更新图片

$(imageobj).attr('src', $(imageobj).attr('src') + '?' + Math.random() );

这是很实用的技巧,曾经有人问明河,为什么他已经修改了图片的src,但图片没变化呢?原因在于缓存,给图片路径后加个随机数参数即可。

加载多张图片,判断加载完成状态

 var totalimages = 10;
var loadedimages = 0;
$("").load(function() {
++loadedimages;
if(loadedimages == totalimages){
//全部图片加载完成时…..
}
});

双击不选中文本

 var clearSelection = function () {
if(document.selection && document.selection.empty) {
document.selection.empty();
} else if(window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}

$(element).bind('dblclick',function(event){
clearSelection();
});

对一个列表进行排序

 

  • cloud

  • sun

  • rain

  • snow


  • var items = $('.to_order li').get();

    items.sort(function(a,b){
    var keyA = $(a).text();
    var keyB = $(b).text();
    if (keyA < keyB) return -1;
    if (keyA > keyB) return 1;
    return 0;
    });
    var ul = $('.to_order');
    $.each(items, function(i, li){
    ul.append(li);
    });

(中文无效)
绑定右击事件

 $(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});

 扩展jquery的对象选择器

 $.extend($.expr[':'], {
//选择器名
moreThanAThousand : function (a){
return parseInt($(a).html()) > 1000;
}
});
$(document).ready(function() {
$('td:moreThanAThousand').css('background-color', '#ff0000′);
});

 检查对象是否存在

if ($("#elementid").length) {
//……
}

取消一个ajax请求

var req = $.ajax({
type: "POST",
url: "someurl",
data: "id=1″,
success: function(){

}
});
//取消ajax请求
req.abort()

检查cookies是否可用

$(document).ready(function() {
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不能用……..
}
});

获取当前元素在元素集内的索引值

 $("ul > li").click(function () {
var index = $(this).prevall().length;
});
//如果用的是jquery1.4,明河推荐使用以下方法:
$("ul > li").click(function () {
var index = $(this).index();
});

 让一个元素相对于屏幕居中

jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() – this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() – this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}
$(element).center();

这个方法非常实用,明河严重推荐收藏
获取当前页面的URL

$(document).ready(function() {
var pathname = window.location.pathname;
});

  

如何隐藏除了特定选择器下的全部对象

 $('#target div:not(#exclude)').hide();
//或者
$('#target').children().filter(':not(#exclude)').hide();

filter()起到过滤的作用。

寻找带有指定字符串的元素

var foundin = $('*:contains(" 明河")');

获取垂直滚动距离

alert($(document).scrollTop());

scrollTop()非常实用的一个方法。
向表格追加一行数据

 $('#myTable tr:last').after('…');

超过一个属性时的过滤

var elements = $('#someid input[type=sometype][value=somevalue]').get();

让cookies在X分钟后过期

var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });

选择从第一个到第X个的元素

//从第一个到第10个
$('a').slice(0,10);
//或者
$('a:lt(10)');

获取客户端的IP

 $.getJSON("http://jsonip.appspot.com?callback=?",function(data){
alert( "你的IP:" + data.ip);
});

这是利用了jsonip.appspot.com提供的取IP服务。
解析XML数据源




1
title1
desc1


2
title2
desc2




$.get('file.xml',{},function(data){
$('item',data).each(function(){
var $this       = $(this);
var id             = $this.find('id').text();
var title         = $this.find('title').text();
var description = $this.find('description').text();
//do something …
});
});

获取在id中的数字



$("#sites a").click(function(){
var $this     = $(this);
var nmb     = $this.attr('id').match(/site_(d+)/)[1];

});

将类似12343778 转成 12.343.778的形式

 var delimiter = '.';
$('#result').html()
.toString()
.replace(new RegExp("(^\d{"+($this.html().toString().length%3||-1)+"})(?=\d{3})"),"$1″ + delimiter)
.replace(/(d{3})(?=d)/g,"$1″ + delimiter);

这个正则值得收藏,颇为经典。
向firebug的控制面板发送消息

 jQuery.fn.log = function (msg) {
console.log("%s: %o", msg, this);
return this;
};
$('#some_div').find('li.source > input:checkbox').log("sources to uncheck").removeAttr("checked");

获取图片的宽高

var img = $('#imageid');
var theImage = new Image();
theImage.src = img.attr("src");
alert("Width: " + theImage.width);
alert("Height: " + theImage.height);
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号