這是一篇「備用手冊」性質的整理,收錄日常開發中反覆用到的 jQuery 小技巧,遇到需求時直接翻來抄即可。
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
使用 CDN 除了有機會命中快取、加快載入,也能分擔自身伺服器的流量。
$(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;
});
});
$.extend($.expr[':'], {
moreThanAThousand: function (a) {
return parseInt($(a).html()) > 1000;
}
});
$(document).ready(function () {
$('td:moreThanAThousand').css('background-color', '#ff0000');
});
if ($("#elementid").length) {
// ……
}
var req = $.ajax({
type: "POST",
url: "someurl",
data: "id=1",
success: function () { }
});
req.abort(); // 取消請求
$(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();
var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });
需搭配 jquery.cookie 外掛使用。
$('a').slice(0, 10);
// 或者
$('a:lt(10)');
$.getJSON("https://jsonip.appspot.com?callback=?", function (data) {
alert("你的IP:" + data.ip);
});
$.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 …
});
});
$("#sites a").click(function () {
var $this = $(this);
var nmb = $this.attr('id').match(/site_(\d+)/)[1];
});
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);
這段正則頗為經典,值得反覆琢磨。
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() 才能取得原始檔的真實解析度。