jQuery基本用法

2026-06-16 05:22:14

.css()#

方法可變更或取得元素的樣式。參數可有數種型式,先以 object 為例。

jQuery script 片段 (借用前節 html)

$("*.menu").css({textAlign:"justify"});

$("*.menu li").css({backgroundColor:"aqua",display:"inline-block",marginRight:"0.5em"});

html 動態變為

.addClass(), .removeClass()#

方法可加入或移除元素的 class 屬性的名稱值。參數為 String type 。

jQuery script 片段,替元素加 class 名稱 (借用前節 html)

$("*.menu").addClass("poem");

$("li>strong").addClass("author");

html 動態變為

jQuery script 片段,接著假設在不同時候,移除元素 class 名稱,如,

$("*.menu").removeClass("poem");

$("li>strong").removeClass();

html 動態變為

.on(events, handler)#

方法指定偵聽的事件名稱 (events, String type) 及事件處理函數 (handler, Function type) 。

假設 html 片段

涼州詞 王翰

葡萄美酒夜光杯

欲飲琵琶馬上催

醉臥沙場君莫笑

古來征戰幾人回

jQuery script 片段,替元素加 click 使用者互動的事件 (interactive event),如,

var c1=function(){

$("*.item>*:nth-child(2)>*:nth-child(2n)").css({backgroundColor:"#eee"});

$(this).remove();

};

$("*.item button").on("click", c1);

使用者在 [上色] button 按下執行鍵後, html 動態變為

涼州詞 王翰

葡萄美酒夜光杯

欲飲琵琶馬上催

醉臥沙場君莫笑

古來征戰幾人回

.ready(handler)#

方法為文件 完整讀入完畢 (包括完成載入外部來源) 的特別事件函數。參數 handler (Function type) 是事件處理函數。

jQuery script 片段

jQuery(document).ready(function(){/*DOM 完整載入後才執行的 script 區段*/});

建議以簡化語法,

jQuery(function(){/*DOM 完整載入後才執行的 script 區段 */});

jQuery script 片段,使用 jQuery 代稱,如 $ ,以事件處理函數的參數指定代稱,可防止與其它 Library 發生名稱衝突。

jQuery(document).ready(function($){/*DOM 完整載入後才執行的 script 區段,可安全使用 $ */});

建議以簡化語法,

jQuery(function($){/*DOM 完整載入後才執行的 script 區段,可安全使用 $ */});