DIV CSS 佈局教程網

用 jQuery 做一個簡單的九宮格:滑過就依序填入數字
編輯:JQuery特效代碼     

這是一個小而完整的小練習:畫面上一個 3×3 的九宮格按鈕,滑鼠移過哪一個,就把它的數字依序接寫到下方的輸入框裡,不重複、不亂序。它示範了 each 搭配索引、以及用字串搜尋做去重的基本手法。

完整程式碼

<input type="button" value="1"/>
<input type="button" value="2"/>
<input type="button" value="3"/><br>
<input type="button" value="4"/>
<input type="button" value="5"/>
<input type="button" value="6"/><br>
<input type="button" value="7"/>
<input type="button" value="8"/>
<input type="button" value="9"/><br>
<input type="text" value=""/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var items = "";
jQuery(function(){
  $("input:button").each(function(index){
    $(this).mouseover(function(){
      if (items.indexOf($('input').eq(index).val()) == -1) {
        items += $('input').eq(index).val();
        $('input:text').val(items);
      }
    });
  });
});
</script>

程式在做什麼

$("input:button").each(function(index){...}) 一次選到九個按鈕,並把各自的索引 capture 在 index 裡。接著為每個按鈕綁上 mouseover,觸發時透過 $('input').eq(index) 精準取回「自己」的值——這是閉包搭配索引的常見用法。

去重靠 items.indexOf(...) == -1:只有尚未出現過的數字才會被附加到字串後面。最後把 items 寫回文字框,就完成了「依滑過順序記錄」的效果。

可以改進的地方

這個範例用字串當集合,缺點是無法區分 1 與 11——若按鈕值不只 0–9,indexOf 會誤判(搜尋 "1" 會在 "11" 裡命中)。要更嚴謹,可以改用陣列搭配 $.inArray(),或以 join('') 分隔後再比對。

另外有兩個實務建議。第一,$('input').eq(index) 每次都重新查詢整個文件,其實在 each 迴圈裡直接用 $(this).val() 就好,不必繞一圈。第二,事件建議綁 mouseenter 而非 mouseover:後者會因滑過子元素而重複觸發,前者只在真正進入元素時觸發一次。

虽然只是小練習,但「用 each 取得索引 → 閉包保存 → 事件內取回自身」這條思路,在寫 todo list、投票元件、表單 repeater 時都會一再出現,值得弄清楚。

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