jquery实用代码片段集合

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

jquery实用代码片段集合

  2020-05-12 我要评论

加载google的jquery库

<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>

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

修改图片src更新图片

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

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

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

var totalimages = 10;
var loadedimages = 0;
$("
<img/>").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();
});

对一个列表进行排序

<ul>
<li>cloud</li>
<li>sun</li>
<li>rain</li>
<li>snow</li>
</ul

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('<tr></tr>');

超过一个属性时的过滤

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数据源

<?xml version="1.0?>
<result>
<item>
<id>1</id>
<title>title1</title>
<description>desc1</description>
</item>
<item>
<id>2</id>
<title>title2</title>
<description>desc2</description>
</item>
<!– … –>
</result>

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

获取在id中的数字

<div id="sites">
<a id="site_1″ href="http://siteA.com">siteA</a>
<a id="site_2″ href="http://siteB.com">siteB</a>
<a id="site_3″ href="http://siteB.com">siteC</a>

</div>

$("#sites a").click(
function(){
var $this &nbsp;&nbsp; &nbsp;= $(this);
var nmb &nbsp;&nbsp; &nbsp;= $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);

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们