所以我有一个复选框列表,我在其中将它们的值推送到一个数组,该数组仅限于 3 个选择。这些选择会显示在页面上的 div 中。推送部分工作正常。我遇到的问题是当我取消选择或取消选中这些框时,我希望从数组中弹出或删除值,这反过来又从 View 中删除或分离它们。
/* checkboxes */
selections = new Array();
$("input[type='checkbox']").change(function () {
var maxAllowed = 3;
var cnt = $("input[type='checkbox']:checked").length;
var checkIt = $("input[type='checkbox']");
var chkboxVal = $(this).val();
//reset selections counter
if (cnt <= maxAllowed) {
$('.selCount .counter').html(selReset-cnt);
selections.push(chkboxVal);
} else if (cnt > maxAllowed) {
$(this).prop("checked", "");
$(this).unbind("click");
$(this).css("cursor","default");
}
var Item1 = selections[0];
var Item2 = selections[1];
var Item3 = selections[2];
var bindedChoice1 = $('<div class="sel1">'+Item1+'</div>');
var bindedChoice2 = $('<div class="sel2">'+Item2+'</div>');
var bindedChoice3 = $('<div class="sel3">'+Item3+'</div>');
//Index of check
if (cnt == 1) {
$(".catSelBar").append(bindedChoice1);
console.log(selections);
}
if (cnt == 2) {
$(".catSelBar").append(bindedChoice2);
console.log(selections);
}
if (cnt == 3) {
$(".catSelBar").append(bindedChoice3);
console.log(selections);
}
if(!$(this).prop("checked") && cnt == 1 && $('.catSelBar div').hasClass("sel1")) {
$(".sel1").detach();
selections.pop();
console.log(selections);
}
if(!$(this).prop("checked") && cnt == 1 && $('.catSelBar div').hasClass("sel2")){
$(".sel2").detach();
selections.pop();
console.log(selections);
}
if(!$(this).prop("checked") && cnt == 2 && $('.catSelBar div').hasClass("sel3")) {
$(".sel3").detach();
selections.pop();
console.log(selections);
}
}); //checkbox change function
最佳答案
当我过去做过类似的事情时,有时我会重建选择数组。
下面是一些示例代码:
$(function() {
var selections = [],
render_selections = function() {
$('#selections').html(selections.join(', '));
};
$('input[type="checkbox"]').change(function() {
selections = $.map($('input[type="checkbox"]:checked'), function(a) { return a.value; })
render_selections();
});
});
这是一个示例 fiddle :http://jsfiddle.net/v4w25pe5/
关于javascript - 复选框将其值推送到空数组中,但在 jQuery 中未选中时弹出或移动值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25269298/