實用jquery代碼片段集合

來源: 我想網  發布時間: 2010-08-03 15:38  閱讀: 1893 次  推薦: 0   原文鏈接   [收藏]  
 
[1] 實用jquery代碼片段集合
[2] 實用jquery代碼片段集合

加載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;
});

 

[第1頁][第2頁]
0
0
 
標簽:jquery
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()