0

我认为这很简单,但我无法弄清楚为什么#type2不能点击。

<input type="radio" id="type1" name="group1" checked>

<input type="radio" id="type2" name="group1">

<input type="text" class="type1">

<input type="text" class="type2" disabled>

<script>

function toggle() {
    if ($('#type1').attr('checked', true)) {
        $('.type1').attr('disabled', false);
        $('.type2').attr('disabled', true);
    }
    else if ($('#type2').attr('checked', true)) {
        $('.type1').attr('disabled', true);
        $('.type2').attr('disabled', false);
    }
}

$(document).ready(function() {
    toggle();
});

</script>

我看不出有什么问题。任何帮助都会很棒,谢谢。

4

4 回答 4

2

尝试:

function toggle() {
    if ($('#type1').is(':checked')) {
        $('.type1').attr('disabled', false);
        $('.type2').attr('disabled', true);
    }
    else if ($('#type2').is(':checked')) {
        $('.type1').attr('disabled', true);
        $('.type2').attr('disabled', false);
    }
}

示例:http: //jsfiddle.net/andrewwhitaker/z5Wbv/1/

.attr您使用的版本 #type1'checked属性设置为 true。您可以使用is, 和:checked选择器来确定是否选中了复选框/单选按钮。

于 2012-10-11T22:15:43.707 回答
2

您使用的是 .attr 而不是 .prop。

.attr 用于属性,.prop 用于属性。属性 = 选中、选中、禁用。

文档:http ://api.jquery.com/prop/

要确定是否选中了复选框,

if ( elem.checked )
if ( $(elem).prop("checked") )
if ( $(elem).is(":checked") )
于 2012-10-11T22:17:21.723 回答
0

工作演示** http://jsfiddle.net/YUhFw/

需要纠正的几件事:)

  • 检查是否使用检查.is(":checked")
  • 将其附加到单击事件。
  • 相应地附加和分离disabled属性。

希望它适合原因:)

代码

function toggle() {
    if ($('#type1').is(':checked')) {
        $('.type1').removeAttr('disabled');
        $('.type2').attr('disabled', true);
    }
    else if ($('#type2').is(':checked')) {
        $('.type1').attr('disabled', true);
        $('.type2').removeAttr('disabled');
    }
}

$(document).ready(function() {
    $("input[type=radio]").click(function() {
        toggle();
    });
});​
于 2012-10-11T22:19:16.167 回答
0

不是在这里检查条件。

你正在设置它 which is always true.. 试试这个

if ($('#type1').is(':checked')){

也使用.prop() 代替.attr()因为这确实不是属性,而是单选按钮的属性。您的代码应如下所示

function toggle() {
    if ($('#type1').is(':checked')) {
        $('.type1').prop('disabled', false);
        $('.type2').prop('disabled', true);
    }
    else if ($('#type2').is(':checked')) {
        $('.type1').prop('disabled', true);
        $('.type2').prop('disabled', false);
    }
}
于 2012-10-11T22:19:21.427 回答