DIV CSS 佈局教程網

jQuery 實用代碼片段大集合:20 多個可以直接複用的技巧
編輯:JQuery特效代碼     

這是一篇「備用手冊」性質的整理,收錄日常開發中反覆用到的 jQuery 小技巧,遇到需求時直接翻來抄即可。

載入 Google CDN 上的 jQuery

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

使用 CDN 除了有機會命中快取、加快載入,也能分擔自身伺服器的流量。

更新圖片 src 卻沒生效?加個隨機參數

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

原因通常是瀏覽器快取。在網址後附加隨機查詢參數,就能強制重新請求。

批次載入多張圖片並判斷完成狀態

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();
});

對列表進行排序

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

注意:這種字串比較對中文無效,中文排序需改用 localeCompare 或轉拼音處理。

綁定右鍵事件

$(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 () { }
});
req.abort();  // 取消請求

檢測瀏覽器是否支援 cookie

$(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;
});
// jQuery 1.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();

加上了 scrollTop/scrollLeft 的補償,捲動後依然能正確置中,這個方法值得收藏。

取得當前頁面的路徑

$(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());

向表格追加一行

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

多條件屬性過濾

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

讓 cookie 在 X 分鐘後過期

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

需搭配 jquery.cookie 外掛使用。

選取第 1 到第 X 個元素

$('a').slice(0, 10);
// 或者
$('a:lt(10)');

取得客戶端 IP

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

解析 XML 資料

$.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);

用 jQuery 直接讀 width() 有時會拿到被 CSS 縮放後的尺寸,改用 new Image() 才能取得原始檔的真實解析度。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved