[英]Problem adding options to a drop down list using jQuery
我正在嘗試使用jquery在另一個下拉列表中選擇特定列表項時填充一個下拉列表,但是由於某些原因,這些選項是在下拉列表之外創建的,這是我的代碼,
function makeModel(obj){
model = new Array();
model[0] = new Array( '212', 'Ace', 'Aceca', 'Cobra', 'Superblower');
model[1] = new Array( '145', '146', '147', '147 3 Door', '147 5 Door', '155', '156', '159', '164', '166', '33', '75', '90', 'Alfasud', 'Alfetta', 'Arna', 'Brera', 'GT', 'GTV', 'Giulietta', 'Gold Cloverleaf', 'Mito', 'SZ', 'Spider', 'Sprint');
model[2] = new Array( 'Rocsta');
var curSel=obj.options[obj.selectedIndex].value ;
var x;
$('#replace').html("<select name=\"test\" id=\"test\">");
for (x in model[curSel])
{
$('#replace').append("<option>" + model[curSel][x] + "</option>");
}
$('#replace').append("</select>");
}
HTML:
<form>
<fieldset>
<p>
<label for="test">Make: </label>
<select name="test" id="test" onchange="makeModel(this);">
<option>Select one</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</p>
</fieldset>
</form>
<div id="replace"></div>
我敢肯定這是我自己某個地方的邏輯錯誤,但我找不到它!
因此,任何幫助將不勝感激,thanx!
您將附加到replace div框,而不是select輸入元素。
更改所追加到(而不是#replace,你將被使用#TEST) 但是正被同時用於選擇插入到所述替換區域,並用於執行插入初級選擇輸入#TEST的ID是什么。 因此,您需要將其更改為諸如“ sub”之類的內容,最終得到如下所示的內容:
function makeModel(obj){
model = new Array();
model[0] = new Array( '212', 'Ace', 'Aceca', 'Cobra', 'Superblower');
model[1] = new Array( '145', '146', '147', '147 3 Door', '147 5 Door', '155', '156', '159', '164', '166', '33', '75', '90', 'Alfasud', 'Alfetta', 'Arna', 'Brera', 'GT', 'GTV', 'Giulietta', 'Gold Cloverleaf', 'Mito', 'SZ', 'Spider', 'Sprint');
model[2] = new Array( 'Rocsta');
var curSel=obj.options[obj.selectedIndex].value ;
var x;
$('#replace').html("<select name=\"test\" id=\"sub\">");
for (x in model[curSel])
{
$('#sub').append("<option>" + model[curSel][x] + "</option>");
}
}
這樣就可以了。 看這里。
$('#replace').append("</select>");
沒有必要。 並且實際上會創建另一個select元素或只是錯誤。
在您的問題中,您將選項附加到div上,而不是實際添加到選擇中。 我會這樣修復。
function makeModel(obj){
model = new Array();
model[0] = new Array( '212', 'Ace', 'Aceca', 'Cobra', 'Superblower');
model[1] = new Array( '145', '146', '147', '147 3 Door', '147 5 Door', '155', '156', '159', '164', '166', '33', '75', '90', 'Alfasud', 'Alfetta', 'Arna', 'Brera', 'GT', 'GTV', 'Giulietta', 'Gold Cloverleaf', 'Mito', 'SZ', 'Spider', 'Sprint');
model[2] = new Array( 'Rocsta');
var curSel=obj.options[obj.selectedIndex].value ;
var x;
var $replace = $('#replace');
var $sel = $('<select name="test" id="sub">').appendTo($replace);
$.each(model[curSel], function(i,v){
{
var $option = $("<option>" + v + "</option>");
$sel.append($option);
})
}
一般而言,使用jQuery更好,而不是使用jQuery for in
就好像擴展了原型一樣,您可能會撿到很多您料想不到的垃圾!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.