我构建了这些复选框,并使用iCheck JS库设置了样式。 像这样:
<div class="interests">
<div class="category-title mt-3">
<h4 class="card-title mb-0">Interesses <span class="small"><a href="#" id="resetInterests">(wissen)</a></span></h4>
<hr>
</div>
<div class="sidebar-list">
<ul class="skin-square skin searchinterests">
<?php
foreach ($interests as $int) {
$id = "interest-" . $int->interest_id;
?>
<li>
<input type="checkbox" id="<?=$id?>" name="interests[]" value="<?=$int->interest_id?>">
<label for="<?=$id?>">
<?=$int->full_name?>
</label>
<span class="pull-right">49</span>
</li>
<?php
}
?>
</ul>
</div>
然后在我的JavaScript中,我得到了以下代码:
var searchSelectedInterests = [];
$(document).ready(function(){
'use strict';
// Square Checkbox & Radio
$('.skin-square input').iCheck({
checkboxClass: 'icheckbox_square-blue'
});
$('.searchinterests input').on('ifChecked', function(event) {
var interestid = event.target.value;
searchSelectedInterests.push(interestid);
performSearch();
});
$('.searchinterests input').on('ifUnchecked', function(event) {
var interestid = event.target.value;
var arrayPos = $.inArray(interestid, searchSelectedInterests);
if (arrayPos > -1) {
searchSelectedInterests.splice(arrayPos, 1);
}
performSearch();
});
$('#resetInterests').on('click', function(e) {
e.preventDefault();
$("input[name='interests[]']").iCheck('uncheck');
});
});
问题在于,因为iCheck('uncheck')会为我要取消选中的每个复选框触发'ifUnchecked'事件(如果选中了10个复选框,它将执行10次AJAX搜索请求)。这给了我不想要的结果,我希望所有复选框都未选中,而ifUnchecked事件被触发一次。