0
使用.prop()將變量作爲id選擇器時出現問題。最終,我希望在選中時檢查複選框,如果在選中時選中,則取消選中。.prop()未選擇帶變量選擇器的複選框
這是狀態/城市列表的一部分,當您單擊列表項目父項時,該列表將崩潰並展開。
小提琴:https://jsfiddle.net/xeud8khg/
$('#expList input:checkbox').unbind('click').click(function() {
var clicked = "#" + event.target.id;
$(clicked).prop('checked', true);
console.log(clicked); //To see that the right id was selected.
return false;
});
更新:二手Barmar的答案補充的複選框,並單擊標籤上的切換。我敢肯定有一個更清潔的方式,但這種工作:
//Fake checkbox
$('#expList input:checkbox').off('mouseup').mouseup(function(event) {
var clicked = "#" + event.target.id;
if ($(clicked).is(':checked'))
$(clicked).prop('checked', false);
else
($(clicked).prop('checked', true));
return false;
});
//Fake label
$('#expList label').off('mouseup').mouseup(function(event) {
labelID = "#" + $(this).attr('for');
if ($(labelID).is(':checked'))
$(labelID).prop('checked', false);
else
($(labelID).prop('checked', true));
return false;
});
更新小提琴:https://jsfiddle.net/fasr5frp/
'.unbind()'已過時,你應該使用'.off()'。你可以使用'$(this)'或'$(event.target)'而不是搜索ID。 – Barmar
使用'event'作爲全局變量是不可移植的,它應該是回調的參數。 – Barmar
如果你在'.prop()'後面設置了一個斷點,你可以看到該方框被選中,但是在函數返回後有些東西沒有被選中。我不知道爲什麼,因爲你正在防止默認。 – Barmar