我需要检查一个检查箱的检查财产,并使用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>

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


当前回答

使用JavaScript:

let checkbox = document.getElementById('checkboxID');

if(checkbox.checked) {
  alert('is checked');
} else {
  alert('not checked yet');
}

其他回答

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

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

饰 Fiddle

这对我来说工作:

/* isAgeSelected being id for checkbox */

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

下面是一个例子,包括启动显示/隐藏,以匹配页面加载时检查箱的状态;考虑到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').bind('change', function () {

   if ($(this).is(':checked'))
     $("#txtAge").show();
   else
     $("#txtAge").hide();
});

jQuery 1.6 以上

$('#isAgeSelected').prop('checked')

jQuery 1.5 或更低

$('#isAgeSelected').attr('checked')

任何 jQuery 版本

// Assuming an event handler on a checkbox
if (this.checked)

所有的信用都交给Xian。