使用jQuery检查复选框时禁用选择元素 [英] Disabling select element when checkbox is checked with jQuery
问题描述
我想制作一个脚本,在检查所需的复选框时禁用选择表单元素。由于会有更多次我会使用这个,我想把它作为一个函数,它将目标选择ID作为参数。问题是,当我将id作为参数传递时,此函数不起作用。相反,它似乎使用硬编码的ID。
< select id =worldSelectclass =select name =world>
< input id =worldcbtype =checkboxchecked =yesvalue =anyname =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/
I want to make a script which will disable a select form element upon checking desired checkbox. Since there will be more times I will use this, I wanted to make it as a function which takes target selection id as an argument. The problem is, this function doesn't work when I'm passing the id as argument. On the contrary, it seems to work with hard-coded 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);
});
You can't invoke the same function twice and expect the function to remember the id variable.
However you could do something like this:
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);
});
Fiddle: http://jsfiddle.net/4ZBne/1/
这篇关于使用jQuery检查复选框时禁用选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!