2012-11-09 63 views
-6

我需要幫助將2個jQuery代碼合併爲一個。我將在同一頁上使用這兩個代碼。這是我的基本的HTML代碼:如何將2個jQuery代碼合併爲一個

<div class="filter"> 
    <label><input type="checkbox" id="one" />One</label> 
    <label><input type="checkbox" id="two" checked="checked" />Two</label> 
    <label><input type="checkbox" id="three" />Three</label> 
    <label><input type="checkbox" id="four" checked="checked" />Four</label> 
    <label><input type="checkbox" id="five" />Five</label> 
    <label><input type="checkbox" id="six" checked="checked" />Six</label> 
    <label><input type="checkbox" id="seven" checked="checked" />Seven</label> 
    <label><input type="checkbox" id="eight" />Eight</label> 
    <label><input type="checkbox" id="nine" checked="checked" />Nine</label> 
    <label><input type="checkbox" id="ten" />Ten</label> 
</div> 

這是第一個jQuery代碼:

$(function() { 
    var list = $("div.filter"); 
    var origOrder = list.children(); 
    var i, checked = document.createDocumentFragment(); 
    var unchecked = document.createDocumentFragment(); 
    for (i = 0; i < origOrder.length; i++) { 
    if (origOrder[i].getElementsByTagName("input")[0].checked) { 
      checked.appendChild(origOrder[i]); 
     } else { 
      unchecked.appendChild(origOrder[i]); 
     } 
    } 
    list.append(checked).append(unchecked); 
}); 

...這是第二個:

$(function() { 
    var list = $("div.filter"); 
    var origOrder = list.children(); 
    list.on("click", ":checkbox", function() { 
     var i, checked = document.createDocumentFragment(); 
     var unchecked = document.createDocumentFragment(); 
     for (i = 0; i < origOrder.length; i++) { 
      if (origOrder[i].getElementsByTagName("input")[0].checked) { 
       checked.appendChild(origOrder[i]); 
      } else { 
       unchecked.appendChild(origOrder[i]); 
      } 
     } 
     list.append(checked).append(unchecked); 
    }); 
}); 

這裏是jsFiddle鏈接。
謝謝。

+6

什麼問題?你卡在哪裏? –

回答

3

由於點擊處理程序和其他腳本本質上是相同的代碼,因此可以將其中一個轉換爲函數並按名稱引用它。

$(function() { 
    var list = $("div.filter"); 
    var origOrder = list.children(); 

    function doWhateverThisDoes() { 
     var i, checked = document.createDocumentFragment(); 
     var unchecked = document.createDocumentFragment(); 
     for (i = 0; i < origOrder.length; i++) { 
      if (origOrder[i].getElementsByTagName("input")[0].checked) { 
       checked.appendChild(origOrder[i]); 
      } else { 
       unchecked.appendChild(origOrder[i]); 
      } 
     } 
     list.append(checked).append(unchecked); 
    } 

    list.on('click', ':checkbox', doWhateverThisDoes); 
    doWhateverThisDoes(); 
}); 
+1

**謝謝@ chao ** – Mikerobenics

+0

+1爲函數名幽默 – silasjmatson