我有多个 checkbox
,如果 checkbox
是 已选择
。选择它时,我希望使用 data-template
中的数据并将其放入 array
中,这样如果选择了多个选项,它就会显示出来。
我做错了什么?
$('.tp-template-check').on('change', function() {
var templateSelection = {};
$('.tp-template-check:checked').each(function() {
templateSelection[$(this).data('template')] = $(this).val();
$('#template-selection-review').html(templateSelection);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="tp-template-check" data-template="Winter">
<input type="checkbox" class="tp-template-check" data-template="Spring">
<input type="checkbox" class="tp-template-check" data-template="Summer">
<input type="checkbox" class="tp-template-check" data-template="Fall">
<div id="template-selection-review"></div>
如果你想使用 object
作为你显示的片段,你必须将 value
设置为复选框的,然后转换结果对象 templateSelection
在将其打印到 #template-selection-review
之前转换为 String:
$('#template-selection-review').html(JSON.stringify(templateSelection));
否则你可以使用数组代替,那么你不需要没有值:
templateSelection.push($(this).data('template'));
希望这对您有所帮助。
片段使用对象:
$('.tp-template-check').on('change', function() {
var templateSelection = {};
$('.tp-template-check:checked').each(function() {
templateSelection[$(this).data('template')] = $(this).val();
});
$('#template-selection-review').html(JSON.stringify(templateSelection));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="tp-template-check" data-template="Winter" value='checkbox1'>
<input type="checkbox" class="tp-template-check" data-template="Spring" value='checkbox2'>
<input type="checkbox" class="tp-template-check" data-template="Summer" value='checkbox3'>
<input type="checkbox" class="tp-template-check" data-template="Fall">
<div id="template-selection-review"></div>
使用数组的代码段:
$('.tp-template-check').on('change', function() {
var templateSelection = [];
$('.tp-template-check:checked').each(function() {
templateSelection.push($(this).data('template'));
});
$('#template-selection-review').html(templateSelection.join('<br>'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="tp-template-check" data-template="Winter" value='checkbox1'>
<input type="checkbox" class="tp-template-check" data-template="Spring" value='checkbox2'>
<input type="checkbox" class="tp-template-check" data-template="Summer" value='checkbox3'>
<input type="checkbox" class="tp-template-check" data-template="Fall">
<div id="template-selection-review"></div>