日常開發中反覆出現的小需求,累積起來就是一份口袋清單。以下 15 個片段都是可以直接複製去用的實戰寫法。
使用者未輸入內容時顯示提示文字,一聚焦就清空,離開時若仍為空則還原:
var swap_val = [];
$(".swap").each(function (i) {
swap_val[i] = $(this).val();
$(this).focusin(function () {
if ($(this).val() == swap_val[i]) { $(this).val(""); }
}).focusout(function () {
if ($.trim($(this).val()) == "") { $(this).val(swap_val[i]); }
});
});
注意這裡用 $.trim() 判斷,使用者只輸入空白也算空值。今天的做法是直接用 HTML5 的 placeholder 屬性,程式碼更少且無障礙支援更好。
var el = $('#id');
el.html(el.html().replace(/word/ig, ''));
$('button.someClass').live('click', someFunction);
在 jQuery 1.4.2 中,delegate 與 undelegate 被引入以取代 live,因為它們提供更好的上下文支援。就 table 而言,過去你會這樣寫:
$("table").each(function () {
$("td", this).live("hover", function () {
$(this).toggleClass("hover");
});
});
現在改用 delegate:
$("table").delegate("td", "hover", function () {
$(this).toggleClass("hover");
});
(更現代的寫法是 $("table").on("hover", "td", handler),live 已在 jQuery 1.9 中移除。)
var newDiv = $('<div></div>');
newDiv.attr('id', 'myNewDiv').appendTo('body');
var cloned = $('#somediv').clone();
if ($(element).is(':visible') == true) {
// 該元素是可見的
}
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();
var arrInputValues = new Array();
$("input[name='table[]']").each(function () {
arrInputValues.push($(this).val());
});
或用更簡短的寫法:$("input[name='table[]']").map(function(){ return $(this).val(); }).get();
// 較繁瑣的寫法
$('#nav li').click(function () {
$('#nav li').removeClass('active');
$(this).addClass('active');
});
// 用 siblings() 簡化
$('#nav li').click(function () {
$(this).addClass('active').siblings().removeClass('active');
});
var tog = false;
$('a').click(function () {
$("input[type=checkbox]").attr("checked", !tog);
tog = !tog;
});
$(document).ready(function () {
$(document).mousemove(function (e) {
$('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
});
$("ul li").click(function () {
window.location = $(this).find("a").attr("href");
return false;
});
$('#theImage').attr('src', 'image.jpg').load(function () {
alert('This Image Has Been Loaded');
});
要注意快取圖片的情境下 load 事件可能不會觸發,實務上通常會加上 if (image.complete) 的檢查。
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) {
// 未啟用 cookie
}
var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });
這裡用到 jQuery 外掛 jquery.cookie;若不引入外掛,就得手動組字串設定 document.cookie。