我正在使用iCheck,并且我希望在状态发生变化时修改元素外观(例如,灰色表示未选中,绿色表示已选中)。这是我到目前为止所尝试的内容:
<!-- the html element I'm trying to change -->
<input type="checkbox" name="status" id="status" class="icheck">
<label for="status">Active</label>
//initializing fields
$('.icheck').each(function() {
var self = $(this),
label = self.next(),
label_text = label.text();
label.remove();
self.iCheck({
checkboxClass: 'icheckbox_line-grey',
radioClass: 'iradio_line-grey',
insert: '<div class="icheck_line-icon"></div>' + label_text
});
});
//how I'm trying to make it work
$('.icheck').on('ifChanged', function() {
var self = $(this);
var label = self.parent();
var label_text = label.text();
var checkboxClass;
var radioClass;
if (label_text == 'Ativado') {
checkboxClass = 'icheckbox_line-grey';
radioClass = 'iradio_line-grey';
label_text = 'Desativado'
} else if (label_text == 'Desativado') {
checkboxClass = 'icheckbox_line-green';
radioClass = 'iradio_line-green';
label_text = 'Ativado'
}
self.iCheck({
checkboxClass: checkboxClass,
radioClass: radioClass,
insert: '<div class="icheck_line-icon"></div>' + label_text
});
});
但是,上面的代码只设置了一次更改元素外观。
为了让它起作用,我在这里缺少什么?
答案 0 :(得分:2)
在 ifChanged 事件中更新iCheck。
参考:
self.iCheck({
checkboxClass: checkboxClass,
radioClass: radioClass,
insert: '<div class="icheck_line-icon"></div>' + label_text
});
现在,您的 ifChanged 事件不再起作用,因为动态创建了一个新元素(iCheck)来替换旧元素。因此,您需要一个不同的事件绑定:委托:
$(document).on('ifChanged', 'input.icheck', function() {
此外,因为您从非活动状态开始,您需要更改此行:
<label for="status">Active</label>
为:
<label for="status">Inactive</label>
//initializing fields
$('.icheck').each(function() {
var self = $(this),
label = self.next(),
label_text = label.text();
label.remove();
self.iCheck({
checkboxClass: 'icheckbox_line-grey',
radioClass: 'iradio_line-grey',
insert: '<div class="icheck_line-icon"></div>' + label_text
});
});
//how I tried to make it work
$(document).on('ifChanged', 'input.icheck', function() {
var self = $(this);
var label = self.parent();
var label_text = label.text();
var checkboxClass;
var radioClass;
if (label_text == 'Active') {
checkboxClass = 'icheckbox_line-grey';
radioClass = 'iradio_line-grey';
label_text = 'Inactive'
} else if (label_text == 'Inactive') {
checkboxClass = 'icheckbox_line-green';
radioClass = 'iradio_line-green';
label_text = 'Active'
}
self.iCheck({
checkboxClass: checkboxClass,
radioClass: radioClass,
insert: '<div class="icheck_line-icon"></div>' + label_text
});
}).trigger('ifChanged');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/iCheck/1.0.2/skins/all.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/iCheck/1.0.2/icheck.min.js"></script>
<input type="checkbox" name="status" id="status" class="icheck">
<label for="status">Inactive</label>