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

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


当前回答

if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}

其他回答

我这样做的方式就是:

if ( $("#checkbox:checked").length ) {       
    alert("checkbox is checked");
} else {
    alert("checkbox is not checked");
}
$(document).ready(function() {    
    $('#agecheckbox').click(function() {
        if($(this).is(":checked"))
        {
            $('#agetextbox').show();
        } else {
            $('#agetextbox').hide();
        }
    });
});

这对我来说工作:

/* isAgeSelected being id for checkbox */

$("#isAgeSelected").click(function(){
  $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});
if($("#checkkBoxId").is(':checked')){
  alert("Checked=true");
}

if($("#checkkBoxId").attr('checked') == true){
  alert("checked=true");
}

我决定发表一个答案,关于如何在没有jQuery的情况下做同样的事情。

var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');

// Just because of IE <333
ageCheckbox.onchange = function() {
    // Check if the checkbox is checked, and show/hide the text field.
    ageInput.hidden = this.checked ? false : true;
};

首先,您将两个元素通过他们的 ID. 然后,您将对检查箱的交换事件分配一个功能,检查检查是否已检查,并适当设置年龄文本字段的隐藏属性。

下面是你试试的技巧。

添加

如果跨浏览器兼容性是一个问题,那么我建议将CSS显示属性设置为无与伦比。

elem.style.display = this.checked ? 'inline' : 'none';

缓慢但跨浏览器兼容。