2011-05-10 90 views
0

我想从我的覆盖(div元素)使用javascript中的数组创建一个下拉列表。Javascript:有关使用javascript创建下拉列表的问题?

在这个例子中,

spcodelist = [u'CA125', u'HCM112', u'HCM147', u'HCM97', u'HKI128', u'HKI158', u'HKS161', u'HKS231', u'TKA230']

下面是相关的代码行:

var pcode_form = document.createElement('form'); 
div.appendChild(pcode_form); 
var pcode_select = document.createElement('select'); 
pcode_form.appendChild(pcode_select); 
var i = 0; 
var spcodelist = document.getElementById('spcodelist').value; 
spcodelist = spcodelist.replace("[",""); 
spcodelist = spcodelist.replace("]",""); 
var spcodearr = new Array(); 
spcodearr = spcodelist.split(', '); 
for (i=0;i<=spcodearr.length;i++){ 
    spcodearr[i] = spcodearr[i].replace(/u'/g,""); 
    spcodearr[i] = spcodearr[i].replace(/'/g,""); 
    var pcode_option = document.createElement('option'); 
    pcode_option.text = spcodearr[i]; 
    pcode_option.value = spcodearr[i]; 
    pcode_select.appendChild(pcode_option); 
} 

有了这个代码,在下拉列表中工作正常,但代码后,将不再工作。我不知道有什么问题?我该如何解决它?还是有更好的解决方案?非常感谢你。

+1

“不起作用”是没有太大的继续。你有没有收到任何错误信息? – RobG 2011-05-10 07:53:01

+0

@RobG我的意思是没有错误信息,但它看起来像代码后,没有产生任何结果。 – Protocole 2011-05-10 08:48:17

回答

0

我不知道你在做什么错,但以下工作正常,应该可以在任何浏览器中工作。我已添加一个删除按钮,以便您可以随时添加和删除选择。

<script type="text/javascript"> 

function addSelect(id) { 

    var div = document.getElementById(id); 
    var pcode_form = document.createElement('form'); 
    pcode_form.id = 'f0'; 
    div.appendChild(pcode_form); 
    var pcode_select = document.createElement('select'); 
    pcode_form.appendChild(pcode_select); 

    var spcodelist = document.getElementById('spcodelist').value; 

    // Do replaces in one go 
    spcodelist = spcodelist.replace(/[\[\]\'u ]/g,''); 

    var spcodearr = spcodelist.split(','); 

    for (var i=0, iLen=spcodearr.length; i<iLen; i++) { 
    pcode_select.options[i] = new Option(spcodearr[i],spcodearr[i]); 
    } 
} 

</script> 

<button onclick="addSelect('d0');">Add select</button> 
<button onclick=" 
    var el = document.getElementById('f0'); 
    el.parentNode.removeChild(el); 
">Remove form</button> 
<div id="d0"></div> 

<textarea id="spcodelist" style="display:none">[u'CA125', u'HCM112', u'HCM147', u'HCM97', u'HKI128', u'HKI158', u'HKS161', u'HKS231', u'TKA230']</textarea> 
+0

非常感谢RobG。现在它工作正常。我想我的错误不是创造新的选择。 – Protocole 2011-05-10 18:39:48