无法控制复选框的选中状态-jQuery [英] Unable to control checkbox checked status - jquery
问题描述
我无法获得此onClick事件来控制复选框的选中状态.有什么想法吗?
I can't get this onClick event to control the checked status of the checkbox.. any thoughts?
init: function () {
$('.billing input[type="checkbox"]').bind('click', function (e) {
e.preventDefault();
iKeyless.page.toggleShippingForm($(e.currentTarget));
});
},
toggleShippingForm: function (el) {
if (el.attr('checked')) {
$('.shipping').parents('.yui-u').addClass('hide');
el.attr('checked', false);
} else {
$('.shipping').parents('.yui-u').removeClass('hide');
el.attr('checked', true);
}
}
它加载了选中的复选框,并且无论我做什么都保持选中状态...
It loads with the checkbox checked and it stays checked regardless of what I do...
推荐答案
应该将它传给this
来引用<input>
元素...尽管您不需要jQuery对象,但这是一个可行的方法版本:
It should just be this
passed in to refer to the <input>
element...though you don't need a jQuery object, here's a working version:
init: function () {
$('.billing input[type="checkbox"]').bind('click', function (e) {
e.preventDefault();
iKeyless.page.toggleShippingForm($(this));
});
},
toggleShippingForm: function (el) {
if (el.attr('checked')) {
$('.shipping').parents('.yui-u').addClass('hide');
el.attr('checked', false);
} else {
$('.shipping').parents('.yui-u').removeClass('hide');
el.attr('checked', true);
}
}
但是,由于 .checked
是DOM属性,因此您可以只需执行此操作即可(无需转换为jQuery对象):
But since .checked
is a DOM property, you can just do this (without converting to a jQuery object):
init: function () {
$('.billing input[type="checkbox"]').change(function (e) {
e.preventDefault();
iKeyless.page.toggleShippingForm(this);
});
},
toggleShippingForm: function (el) {
$('.shipping').parents('.yui-u').toggleClass('hide', el.checked);
}
该元素已经在更改其.checked
状态...只需在change
事件中使用它.如果需要,根据显示方式将.toggleClass('hide', el.checked)
更改为.toggleClass('hide', !el.checked)
.
The element's changing it's .checked
status already...just use it in the change
event. If needed, change the .toggleClass('hide', el.checked)
to .toggleClass('hide', !el.checked)
, depending on which way it should be visible.
这篇关于无法控制复选框的选中状态-jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!