0

我想制作一个脚本,在选中所需的复选框时禁用选择表单元素。由于会有更多次我会使用它,所以我想将它作为一个以目标选择 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);
});
4

2 回答 2

2

您不能两次调用同一个函数并期望该函数记住 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/

于 2012-05-09T20:34:47.353 回答
1

怎么样:

$('#worldcb').click(function() {
    toggleSelection('worldSelect', $(this).is(':checked'));
});

function toggleSelection(sel, chk) {
    $('#' + sel).attr('disabled', chk);
}​

jsFiddle 示例

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

于 2012-05-09T20:38:44.223 回答