问题解释: 我在DOM周围放置了输入元素:
<input type="checkbox" data-filter="markets" data-cid="4" name="checkbox">
<input type="checkbox" data-filter="categories" data-cid="30" name="checkbox">
当我检查任何复选框时,我应该得到这样的JSON对象:
{"categories":["4,5"],"markets":["30,31,32"]}
但是我得到这样的对象:
{"categories":["30,31,32,4,5"],"markets":["30,31,32,4,5"]}
30,31,32 是市场,但 4,5 是类别。也许有人可以告诉我,哪里有问题?
$(document).on('change',"input[name=checkbox]", function() {
page = 0;
var $this = $(this);
if ($this.prop('checked')) {
$this.addClass("checked");
} else {
$this.removeClass("checked");
}
filter();
});
var filter = function() {
var myObject = new Object();
$('.checked').each(function(n) {
var objname = $(this).data('filter');
arr = $('.checked').map(function() {
return $(this).data('cid');
}).get().join(",");
if(arr.length > 0) {
myObject[ objname ] = [ arr ];
}
});
console.log(JSON.stringify(myObject));
return JSON.stringify(myObject);
}
filter();
答案 0 :(得分:2)
尝试
var filter = function () {
var myObject = {};
$('.checked').each(function (n) {
var objname = $(this).data('filter');
var array = myObject[objname] = myObject[objname] || [];
array.push($(this).data('cid'))
});
console.log(JSON.stringify(myObject));
return JSON.stringify(myObject);
}
演示:Fiddle