当页面加载时,Jquery 复选框被选中

6
脚本运行良好,但我想知道是否有一种方法可以避免代码中的重复(DRY方法)。

演示

JS代码:

// Checkbox checked and input disbaled when page loads

$('#checkbox').prop('checked', true);

if ($('#checkbox').is(':checked') == true) {
    $('#textInput').prop('disabled', true);
}


// Enable-Disable text input when checkbox is checked or unchecked

$('#checkbox').change(function() {
    if ($('#checkbox').is(':checked') == true) {
        $('#textInput').prop('disabled', true);
    } else {
        $('#textInput').val('').prop('disabled', false);
    }
});

2
为什么不在HTML中将文本框设置为禁用状态呢? 只有当用户取消选中复选框后,您才需要考虑它是否启用 :) - George
5个回答

14

如果您无法在HTML中默认设置属性:

// Checkbox checked and input disbaled when page loads
$('#checkbox').prop('checked', true);

// Enable-Disable text input when checkbox is checked or unchecked
$('#checkbox').on('change', function() {
    var value = this.checked ? $('#textInput').val() : '';
    $('#textInput').prop('disabled', this.checked).val(value);
}).trigger('change');

演示: http://jsfiddle.net/tusharj/t01a9cxL/1/


3
如果每次加载页面时,你希望复选框被选中且文本框被禁用,最好在HTML中进行设置。
<input type="checkbox" id="checkbox" checked="true" />
<input type="text" id="textInput" disabled=""/>

JavaScript

// Enable-Disable text input when checkbox is checked or unchecked

$('#checkbox').change(function() {
    if ($('#checkbox').is(':checked') == true) {
        $('#textInput').prop('disabled', true);
    } else {
        $('#textInput').val('').prop('disabled', false);
    }
});

1
将您的逻辑分离成可重用的函数:

function checkboxStatus() {
    if ($('#checkbox').is(':checked') == true) {
        $('#textInput').prop('disabled', true);
    } else {
        $('#textInput').val('').prop('disabled', false);
    }
}

// Checkbox checked and input disbaled when page loads
$('#checkbox').prop('checked', true);
checkboxStatus();

// Enable-Disable text input when checkbox is checked or unchecked
$('#checkbox').change(checkboxStatus);

1
简单地说,就像jQuery一样,有许多方法可以完成。
$('#checkbox').prop( 'checked', true ); // when intially checked
$('#checkbox').change(function(){
     $('#textInput').prop('disabled', $(this).is(':checked'));
     if(!$(this).is(':checked')){
       $('#textInput').val('')
     }
}).change(); //intially trigger the event change

Fiddle

可以翻译为:

{{链接1: Fiddle}}


@Tushar 我误解了,抱歉。 - Sudharsan S

1
您可以使用以下代码更少地实现相同的结果:

更新的 Fiddle

// Checkbox checked and input disbaled when page loads
$('#checkbox').prop('checked', true);
$('#textInput').prop('disabled', true);

// Enable-Disable text input when checkbox is checked or unchecked
$('#checkbox').change(function () {
    var checked = $(this).is(':checked') == true;
    $('#textInput').prop('disabled', checked);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接