我正在尝试获取已选中的复选框的顺序。
<ul class="dropdown-content checkboxes">
<li><label><input type="checkbox" />Billy</label></li>
<li><label><input type="checkbox" />Jacob</label></li>
<li><label><input type="checkbox" />Bob</label></li>
<li><label><input type="checkbox" />Alexandren</label></li>
<li><label><input type="checkbox" />Erren</label></li>
<li><label><input type="checkbox" />Stewgart</label></li>
<li><label><input type="checkbox" />Jillian</label></li>
<li><label><input type="checkbox" />Other</label></li>
</ul>
我想出了这个,但我无法获得选中复选框的顺序。我只能获取仅检查的列表。
$(":checkbox").click(function() {
console.log($(":checked").length);
var i = 0;
checked = true;
$(':checkbox').each(function() {
if (this.checked == false) {
i++;
if (i === 8) {
checked = false;
}
}
});
});
我如何获得检查顺序的数据?例如“按此顺序选中复选框 1, 6, 3 ,2”
您将跟踪选中的复选框,例如在数组中
var order = [];
$("[type=checkbox]").on('change', function() { // always use change event
var idx = order.indexOf(this);
if (idx !== -1) { // if already in array
order.splice(idx, 1); // make sure we remove it
}
if (this.checked) { // if checked
order.push(this); // add to end of array
}
// <------------------------------------For demonstration
$('#result').html(JSON.stringify($.map(order, function(elem) {
return $(elem).closest('label').text().trim();
})));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-content checkboxes">
<li><label><input type="checkbox" />Billy</label></li>
<li><label><input type="checkbox" />Jacob</label></li>
<li><label><input type="checkbox" />Bob</label></li>
<li><label><input type="checkbox" />Alexandren</label></li>
<li><label><input type="checkbox" />Erren</label></li>
<li><label><input type="checkbox" />Stewgart</label></li>
<li><label><input type="checkbox" />Jillian</label></li>
<li><label><input type="checkbox" />Other</label></li>
</ul>
<div id="result"></div>
要获取每个复选框的索引,或更准确地说是父 LI,您只需映射它们即可
var map = $.map(order, function(elem) {
return $(elem).closest('li').index();
});
FIDDLE https://jsfiddle.net/3oznqqLf/1/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)