使用 jQuery 选中复选框时禁用选择元素

Disabling select element when checkbox is checked with jQuery

本文关键字:选择 元素 复选框 jQuery 使用      更新时间:2023-09-26

我想制作一个脚本,该脚本将在选中所需的复选框时禁用选择表单元素。由于我会使用它的次数更多,我想将其作为将目标选择 id 作为参数的函数。问题是,当我将 id 作为参数传递时,此函数不起作用。相反,它似乎适用于硬编码的 id。

<select id="worldSelect" class="select" name="world">
<input id="worldcb" type="checkbox" checked="yes" value="any" name="world">
function toggleSelection(id){
    var el = '#' + id;
    if (this.checked) {
        $(el).attr('disabled', 'disabled');
    } else {
        $(el).removeAttr('disabled');
    }
}
$(function() {
    toggleSelection('worldSelect');
    $('#worldcb').click(toggleSelection);
});

您不能两次调用同一个函数并期望该函数记住 id 变量。

但是,您可以执行以下操作:

function toggleSelection(e){
    var el = '#' + e.data;
    console.log(arguments);
    if (this.checked) {
        $(el).attr('disabled', 'disabled');
    } else {
        $(el).removeAttr('disabled');
    }
}
$(function() {
    $('#worldcb').click('worldSelect', toggleSelection);
});​

小提琴:http://jsfiddle.net/4ZBne/1/

怎么样:

$('#worldcb').click(function() {
    toggleSelection('worldSelect', $(this).is(':checked'));
});
function toggleSelection(sel, chk) {
    $('#' + sel).attr('disabled', chk);
}​

jsFiddle 示例

toggleSelection() 函数有两个参数,sel - 选择框的 ID 和 chk,要使用的复选框。