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

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


当前回答

我想这将是简单的

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

其他回答

如果您需要使用 CSS 类作为 jQuery 选择器,您可以执行以下操作:

$(document).ready(function () {
        $('.myOptionCheckbox').change(function () {            
            if ($(this).prop('checked') == true) {
                console.log("checked");           
            }
            else {
                console.log("unchecked");                
            }
        });
    });

它也适用于检查箱和无线电盒。

如果您的 HTML 标签是:

<input type="checkbox"  />

特斯拉使用:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

如果使用POP:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2)如果您的HTML标签是:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"

特斯拉使用:

$(element).attr("checked") // Will return checked whether it is checked="true"

Prop 使用:

$(element).prop("checked") // Will return true whether checked="checked"

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

$('#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(“检查”),它只会返回真实和虚假。

你可以尝试这个代码:

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});

这个代码会帮助你

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});