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

其他回答

我决定发表一个答案,关于如何在没有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';

缓慢但跨浏览器兼容。

试试这,

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

输入类型="checkbox"的检查属性与默认检查属性进行地图,而不是检查属性。

因此,当在一个页面上做点什么时,当一个检查箱在未检查的情况下进行检查时,请使用 prop() 方法。

使用 attr() 或 getAttribute(在纯粹的 JavaScript 中)在这些情况下不是做事的正确方式。

如果元素是相关的检查箱,那么做这样的事情来征收值:

elem.checked

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

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

如何使用 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/