取消选中复选框并单击按钮时隐藏父项
问题描述:
我编写的以下代码应该有一行复选框,选中时,将在单独的div中显示该复选框的标签。取消选中复选框并单击按钮时隐藏父项
<div class="span3" id="bill">
<label class="checkbox">
<input type="checkbox" value="" id="item1" checked="checked">
Item1 - Price
</label>
<label class="checkbox">
<input type="checkbox" value="" id="item2" checked="checked">
Item2 - Price
</label>
</div>
<div class="span3" id="currBill">
<label id="item1_lb">
Item1 - Price
</label>
<label id="item2_lb">
Item2 - Price
</label>
</div>
</div>
<div class="row-fluid">
<button class="btn" id="pay">Pay</button>
</div>
以下JS需要选择时显示标签的护理/未选中的(这是马虎了才知道,所有复选框将稍后从数据库中填写,这只是一般的想法有些地方抱着代码我的问题。)
这两个函数都没有工作,点击功能至少触发,但实际上并没有隐藏任何东西。有任何想法吗?
$(function() {
$('input:checkbox').bind('change',(function() {
$('#'+ithis.id+'_lb').toggle($(this).is(':checked'));
});
$("#pay").click(function() {
$("#bill input[type=checkbox]").each(function() {
if($(this).checked)
{
$(this).parent().hide();
$(this).checked = false;
}
});
});
});
答
您应该使用浏览器控制台检查错误(按Ctrl+Shift+J
)。您有以下错误:
- 在第2行
('change',(function()
,在function
关键字之前删除括号。 -
ithis.id
应该是this.id
。 - 相反检查
if($(this).checked)
应该是像你这样第一:if($(this).is(':checked'))
- 要取消选中该复选框使用
$(this).prop('checked', false);
答
$(this).checked
试图访问一个jQuery集合属性checked
。您可以通过.prop
方法更改元素属性。
if ($(this).prop('checked')) {
...
$(this).prop('checked', false);
+0
谢谢,我的品牌新的网页开发和有这么多来接。 – 2013-02-23 00:35:56
谢谢!看起来,简单地取消选中第二个函数中的复选框不会触发第一个应该隐藏辅助标签的函数,应该如何处理? 我可以重复一行代码我想,但这似乎不正确。 – 2013-02-23 00:41:34
@ dk.win:重复1行没有问题,如果超过2或3,则为此构建一个函数,如下所示:http://jsfiddle.net/qKPGd/1/ – 2013-02-23 00:53:31