我有许多 html 复选框,我试图像这样计数......
jQuery('.mycheckboxes').change(function() {
var count = jQuery('.mycheckboxes:checked').length;
console.log(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
这工作正常,但我想创建一个类似数组的东西,它将按data-section
属性对单击的复选框的计数进行分组,所以我的输出看起来像......
{
data-section-1 : 4,
data-section-2 : 3,
data-section-3 : 1,
};
我最好的方法是什么,我更习惯使用 PHP,所以会尝试创建一个数组,但我应该使用对象吗?
不需要 jquery(远离英国媒体报道)。只需创建一个对象并使用部分属性值作为它的键:
const count = {};
for(let i = 0, list = document.querySelectorAll(".mycheckboxes"); i < list.length; i++)
{
count[list[i].dataset.section] = 0; //set initial values for each section
list[i].addEventListener("change", onChange);
}
function onChange(e)
{
count[e.target.dataset.section] += e.target.checked ? 1:-1;
console.log(count);
}
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句