1

假设我有 id 参数和两个选择框的功能

<select id="one" onchange="Fill(2)"></select>
<select id="two" onchange="Fill(3)"></select>
<select id="three"></select>

我的功能

function Fill(id){  
//some manupulation
$('<option/>').val(substr[0]).html(substr[1]).appendTo('#two');
}

但不是做很多

if(id==2) {$('<option/>').val(substr[0]).html(substr[1]).appendTo('#two');}
if(id==3) {$('<option/>').val(substr[0]).html(substr[1]).appendTo('#three');}

我想要类似的东西

$('<option/>').val(substr[0]).html(substr[1]).appendTo(DYNAMIC);
4

5 回答 5

6

您可以通过使用 id 等来使其更容易select-1select-2然后使用'#select-' + id.

否则,您需要一个从数字映射到拼写数字的映射对象。

于 2012-05-21T16:13:46.340 回答
2
function Fill(id){  
  var index = {
    1: 'one',
    2: 'two',
    3: 'three'; 
  };
  $('<option/>').val(substr[0]).html(substr[1]).appendTo('#' + index[id]);
  // or just, but in this case you need to change the *id* pattern like opt_1, opt_2 etc
  $('<option/>').val(substr[0]).html(substr[1]).appendTo('#opt_' + id);
}
于 2012-05-21T16:13:48.737 回答
0

比你想象的要容易:)

<select id="select-1" onchange="Fill(2)"></select>
<select id="select-2" onchange="Fill(3)"></select>
<select id="select-3"></select>

function Fill(id){ // 
    //some manupulation
    $('<option/>').val(substr[0]).html(substr[1]).appendTo('select-' + id);
}
于 2012-05-21T16:14:49.313 回答
0

将此行添加到 Fill 函数的顶部:

 var DYNAMIC = $(this);
于 2012-05-21T16:18:27.920 回答
0

我将接受 David Thomas 的建议:

<select id="one" onchange="Fill(this);"></select>
<select id="two" onchange="Fill(this);"></select>
<select id="three"></select>

填充函数定义为:

function Fill(select) {
    $('<option />').val(/*..*/).html(/*..*/).appendTo($(select));
}

然后,您可以为您的选择提供您想要的任何 id,并且您不必查询 DOM 来查找对象。

于 2012-05-21T17:06:01.403 回答