2012-05-21 94 views
1

可以說我有id爲paremeter和兩個選擇框jQuery的追加到(通過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); 
+1

我不完全確定,因此評論,但它看起來像你只是想將新的'選項'追加到當前更改的元素?所以...不會'$('

回答

6

您可以通過使用ID如select-1,select-2等,然後使用'#select-' + id使它更容易。

否則,您需要一個從數字映射到拼寫數字的映射對象。

+0

會+1,但票數不足! – jmort253

+0

哇,我不知道我可以這樣做!我在想,它應該會像這樣工作,但沒有嘗試過。我做了200行jQuery的功能,但我不知道這:)))) –

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); 
} 
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); 
} 
0

此行添加到填充功能的頂部:

var DYNAMIC = $(this); 
0

我要去大衛托馬斯的建議:

<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即可找到該對象。