我需要检查一个检查箱的检查财产,并使用jQuery进行检查财产的操作。

例如,如果年龄检查框被检查,那么我需要显示一个文本框进入年龄,否则隐藏文本框。

但下列代码默认返回虚假:

如果($('#isAgeSelected').attr('checked')) { $("#txtAge").show(); } 其他 { $("#txtAge").hide(); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="isAgeSelected"/> <div id="txtAge" style="display:none"> 年龄 已选择 </div>

如何成功查询已检查的房地产?


当前回答

有很多方法可以检查一个检查箱是否被检查:

如何使用 jQuery 查看

if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))

查看例子或文档:

http://api.jquery.com/attr/ http://api.jquery.com/prop/

其他回答

下面是一个例子,包括启动显示/隐藏,以匹配页面加载时检查箱的状态;考虑到Firefox在更新页面时记得检查箱的状态,但不会记得显示/隐藏的元素的状态。

$(function() {
    // initialise visibility when page is loaded
    $('tr.invoiceItemRow').toggle($('#showInvoiceItems').attr('checked'));
    // attach click handler to checkbox
    $('#showInvoiceItems').click(function(){ $('tr.invoiceItemRow').toggle(this.checked);})
});

(与此问题的其他答案的帮助)

事实上,我更喜欢改变事件。

$('#isAgeSelected').change(function() {
    $("#txtAge").toggle(this.checked);
});

饰 Fiddle

这个功能是替代和稳定的:

$('#isAgeSelected').context.checked
(return True/False)

例子:

if($('#isAgeSelected').context.checked){ //if Checkbox is checked then bla bla..
    /*.....*/
}else{
    /*.....*/
}

这对我来说工作:

/* isAgeSelected being id for checkbox */

$("#isAgeSelected").click(function(){
  $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});

以点击进行检查或未检查的检查框进行操作。

$('#customCheck1').click(功能() { if (this.checked) { console.log('checked'); } 其他 { console.log('un-checked'); } ); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" id="customCheck1">

编辑: 如果(boolean = = 真实)虽然.checked 属性可能会返回其他类型的变量。

最好使用.prop(“检查”),它只会返回真实和虚假。