2017-02-10 66 views
2

我有一個數組,我想用來填充兩個不同的選擇框,但我看到一些奇怪的行爲。填充第一個選擇可以正常工作,但是當向第二個選擇框添加相同列表時,第一個選擇將被清除,並且在第二個選擇框中選擇最後一個項目。用選項數組填充兩個選擇框?

var optionList = [] 

optionList.push(new Option("waba", "waba")) 
optionList.push(new Option("shaba", "shaba")) 

$('#first_select').html(optionList); //works fine 
$('#second_select').html(optionList); //clears first select and last item is selected 

JS Fiddle Example

回答

2

我認爲你需要克隆optionList

var optionList = [] 

optionList.push(new Option("waba", "waba")) 
optionList.push(new Option("shaba", "shaba")) 

$('#first').html(optionList); 
$('#second').html($(optionList).clone()); 
1

你要克隆它們使用jQuery.clone這樣的:

$('#first').html(optionList); // append the original options 
$('#second').html($(optionList).clone()); // clone them and append the cloned ones 
3

設置HTML內容都在一個聲明中:

$('#first, #second').html(optionList); 

的jsfiddle:https://jsfiddle.net/tcuow32f/1/

+0

我喜歡這個答案,但不會在我的情況下輕鬆地工作。 –