DIV CSS 佈局教程網

用 jQuery 為列表添加連續編號與留言計數
編輯:JQuery特效代碼     

這個教學將教你如何運用 jQuery 為列表動態添加連續的 CSS 類,做出有層次感的編號列表;第二個範例則示範如何用 jQuery 的 prepend 為留言列表加上序號計數。

1a. 添加 jQuery 程式碼

先在 <head> 之間引入 jQuery,並寫入以下程式:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#step li").each(function (i) {
i = i+1;
$(this).addClass("item" i);
});
});
</script>

這段程式會為每個 <li> 依序加上 item1、item2、item3… 的類名。

1b. CSS 編碼

接著用背景圖為每個類套用不同樣式(step1.png、step2.png、step3.png 等):

#step .item1 {
background: url(step1.png) no-repeat;
}
#step .item2 {
background: url(step2.png) no-repeat;
}
#step .item3 {
background: url(step3.png) no-repeat;
}

2a. 添加連續的內容

同樣的技巧也能用來添加有序內容,這裡用 prepend 為留言列表加上計數:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#commentlist li").each(function (i) {
i = i+1;
$(this).prepend('<span class="commentnumber"> #' i '</span>');
});
});
</script>

它會為每個 <li> 添加一個 <span class="commentnumber"> 計數標記。

2b. CSS

用 position:relative 搭配 position:absolute,把計數放在留言條目的右上角:

#commentlist li {
position: relative;
}
#commentlist .commentnumber {
position: absolute;
right: 0;
top: 8px;
}

透過這兩個範例,你能體會到 jQuery 在動態操作 DOM 與添加樣式上的便利,尤其適合處理資料驅動的列表介面。

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