我需要检查一个检查箱的检查财产,并使用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').bind('change', function () {

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

其他回答

我正在使用 jQuery 1.11.1 并且我也遇到设置和阅读检查箱值问题。

我终于通过这两个功能解决了它:

function setCheckboxValue(checkBoxId, checked) {
    if (checkBoxId && (checked === true || checked === false)) {
        var elem = $('#' + checkBoxId);
        if (checked === true) {
            elem.attr('checked', 'checked');
        } else {
            elem.removeAttr('checked');
        }
    }
}

function isChecked(checkBoxId) {
    return $('#' + checkBoxId).attr('checked') != null;
}

它可能看起来有点脏,但它解决了我在不同类型的浏览器中所有的电缆问题。

我在Firefox 9.0.1中确认了下列工作,以捕捉检查箱邮件的状态变更:

$("#mycheckbox").change(function() {
    var value = $(this).prop("checked") ? 'true' : 'false';                     
    alert(value);
});

由于 jQuery 1.6, jQuery.attr() 的行为已经改变,用户被鼓励不要使用它来恢复一个元素的检查状态。

$("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
                                        // Return value changes with checkbox state
);

另外两种可能性是:

$("#txtAge").get(0).checked
$("#txtAge").is(":checked")

自动化

$(document).ready(function()
{
    $('#isAgeSelected').change(function()
    {
        alert( 'value =' + $('#chkSelect').attr('checked') );
    });
});

HTML

<b> <input type="isAgeSelected" id="chkSelect" /> Age Check </b>

<br/><br/>

<input type="button" id="btnCheck" value="check" />

jQuery

$(document).ready(function()
{
    $('#btnCheck').click(function()
    {
        var isChecked = $('#isAgeSelected').attr('checked');

        if (isChecked == 'checked')
            alert('check-box is checked');
        else
            alert('check-box is not checked');
    })
});

艾雅克斯

function check()
{
    if (isAgeSelected())
        alert('check-box is checked');
    else
        alert('check-box is not checked');
}

function isAgeSelected()
{
    return ($get("isAgeSelected").checked == true);
}

我相信你可以这样做:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}