我有一個複選框列表,像這樣:檢查其點擊第一個複選框
<div class="checkbox-list">
<label><input type="checkbox" value="" /> All items</label><br />
<label><input type="checkbox" value="1" /> First item</label><br />
<label><input type="checkbox" value="2" /> Second item</label><br />
<label><input type="checkbox" value="3" /> Third item</label><br />
<label><input type="checkbox" value="4" /> Forth Checkbox</label>
</div>
我找的行爲是如果我選擇在這個div
(.checkbox-list input[type=checkbox]:first
)所有其他複選框後的第一個複選框被關閉。同樣,如果我選擇除第一個之外的任何一個,則取消選擇第一個。
我在如何檢查第一個單擊是否正在苦苦掙扎?
$(".checkbox-list").on("change", "input[type=checkbox]", function() {
if ($(this).first()) { // <- not working - how do I know if I clicked the first one?
$("input[type=checkbox]:checked", ".checkbox-list").not(this).prop("checked", false);
$(this).prop("checked", true);
} else {
// Uncheck first checkbox
}
});
這裏是一個小提琴,如果你想打轉轉:http://jsfiddle.net/4c7aubqL/1/
只是一個快速的一個:你複選框動態創建? – 2015-04-06 10:11:38
是的,從ajax填充 – janhartmann 2015-04-06 10:17:24
在那種情況下,我已經做了編輯我的答案,使用正確的'.on()'委託使事件保持活躍狀態(就像你一樣)。編輯。 – 2015-04-06 10:21:02