我需要帮助将2个jquery代码合并为一个。我将在同一页面上使用这两个代码。这是我的基本HTML代码:
<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链接 谢谢。
答案 0 :(得分:3)
由于click处理程序和其他脚本基本上是相同的代码,您可以将其中一个转换为函数并按名称引用它。
$(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();
});