问题描述
以下代码将一个复选框和一个标签添加到调用节点.
我的问题在于label.click函数.每当单击标签时,我都想更改匹配复选框的状态.但是,发生的事情是该复选框始终处于未选中状态.出于调试目的,我现在始终将其显式设置为选中状态.
The following code adds a checkbox and a label to the calling node.
My question lies in the label.click function. Whenever the label is clicked I want to change the state of the matching checkbox. What happens however is that the checkbox always ends up unchecked.For debugging purposes I now always explicitly set it to checked.
当我使用firebug遍历代码时,我看到该复选框被选中,然后在离开该功能时再次未被选中.
When I step through the code with firebug I see that the checkbox gets checked and then, when leaving the function it gets unchecked again.
有什么想法吗?
jQuery.fn.AddEndOrStartWith = function(selected, id, action) {
var checkBox = $('<input type="checkbox"></input>');
checkBox.attr("id", id + action);
checkBox.addClass(action + "CheckBox");
checkBox.attr("for", id);
var label = $('<label></label>');
label.attr("for", id + action);
if (selected) {
checkBox.attr("checked", "checked");
label.addClass("lockerClosed");
} else {
label.addClass("lockerOpen");
}
$(this).append(label);
$(this).append(checkBox);
label.click(function() {
/*alert(checkBox.attr("checked"));*/
checkBox.attr("checked", "checked");
/*return true;*/
/*alert(checkBox.attr("checked"));*/
});
}
推荐答案
您需要阻止标签点击处理程序中的默认操作.认为这应该做到:
You need to prevent the default action in your label click handler. Think this should do it:
label.click(function() {
checkBox.attr("checked", "checked");
return false;
});
这是因为您的标签已正确设置了指向其复选框的 for
,因此单击该标签时的默认操作是切换该复选框.
What's going on is that because your label is set up with its for
referring to the checkbox correctly, the default action when clicking on it is to toggle the checkbox.
但是,嗯,如果这就是您要使用点击处理程序进行的全部操作,那么我想您甚至无法使用点击处理程序.但是我不确定是否是这种情况.
Though, um, if that's all you're trying to do with your click handler, I guess you could just not even use a click handler. But I'm not sure whether that's the case.
这篇关于为什么我的复选框总是未选中状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!