DIV CSS 佈局教程網

jQuery 實用小片段整理(15 例)
編輯:JQuery入門技巧     

日常開發中反覆出現的小需求,累積起來就是一份口袋清單。以下 15 個片段都是可以直接複製去用的實戰寫法。

1. 為文字輸入框保留預設提示值

使用者未輸入內容時顯示提示文字,一聚焦就清空,離開時若仍為空則還原:

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 屬性,程式碼更少且無障礙支援更好。

2. 清除元素中的某個字詞

var el = $('#id');
el.html(el.html().replace(/word/ig, ''));

3. 事件委派:live 與 delegate

$('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 中移除。)

4. 把新建元素動態加入 DOM

var newDiv = $('<div></div>');
newDiv.attr('id', 'myNewDiv').appendTo('body');

5. 複製元素

var cloned = $('#somediv').clone();

6. 判斷元素是否可見

if ($(element).is(':visible') == true) {
  // 該元素是可見的
}

7. 自製置中函式

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

8. 把同名元素的值收集成陣列

var arrInputValues = new Array();
$("input[name='table[]']").each(function () {
  arrInputValues.push($(this).val());
});

或用更簡短的寫法:$("input[name='table[]']").map(function(){ return $(this).val(); }).get();

9. 用 siblings() 操作同層元素

// 較繁瑣的寫法
$('#nav li').click(function () {
  $('#nav li').removeClass('active');
  $(this).addClass('active');
});

// 用 siblings() 簡化
$('#nav li').click(function () {
  $(this).addClass('active').siblings().removeClass('active');
});

10. 全選/全不選切換

var tog = false;
$('a').click(function () {
  $("input[type=checkbox]").attr("checked", !tog);
  tog = !tog;
});

11. 取得滑鼠座標

$(document).ready(function () {
  $(document).mousemove(function (e) {
    $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
  });
});

12. 讓整個 li 可點擊

$("ul li").click(function () {
  window.location = $(this).find("a").attr("href");
  return false;
});

13. 確認圖片已載入

$('#theImage').attr('src', 'image.jpg').load(function () {
  alert('This Image Has Been Loaded');
});

要注意快取圖片的情境下 load 事件可能不會觸發,實務上通常會加上 if (image.complete) 的檢查。

14. 檢查瀏覽器是否啟用 cookie

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
}

15. 讓 cookie 過期

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

這裡用到 jQuery 外掛 jquery.cookie;若不引入外掛,就得手動組字串設定 document.cookie。

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