2012-02-28 95 views
0

我需要在组合框中将项目添加特定次数。这是我的代码。将项目追加到组合框中

  for(i=0;i<3;i++) 
    { 
     othercompaniesli.innerHTML= '<select onchange="document.location.href = this.options[this.selectedIndex].value;"><option VALUE="http://www.google.com">'+fStr1[0]+'</option> </select>'; 
    } 

在这里,我要添加的fStr1串3 times.But它增加了只有一个time.That是用于循环工作,但只有项目价值不appending.Only最后的值在组合框中添加。任何人都可以帮助我如何将项目追加到组合框。

回答

1
var tmpStr = '<select onchange="document.location.href = this.options[this.selectedIndex].value;">'; 

for(i=0;i<3;i++) 
{ 
    tmpStr+= '<option VALUE="http://www.google.com">'+fStr1[0]+'</option> '; 
} 

tmpStr = '</select>'; 

othercompaniesli.innerHTML = tmpStr; 
0

尝试othercompaniesli.innerHTML +=

0

由于您使用等于=,这是重新分配到同一个元素

使用append()

$('#othercompaniesli').append('<select onchange="document.location.href = this.options[this.selectedIndex].value;"><option VALUE="http://www.google.com">'+fStr1[0]+'</option> </select>'); 

请注意,您selectoption元素重复,则需要相应地改变它。

0
var select= $('mySelect'); 
var opt = new Option("OptionTitle", "123"); 

select.selectedIndex = InsertNewOption(opt, select[0]); 

function InsertNewOption(opt, element) 
{ 
    var len = element.options.length; 
    element.options[optsLen] = opt; 

    return len; 
} 
+0

这里'select'和'opt'按顺序传递给'InsertNewOption',select是一个jQuery对象而不是元素,所以需要传递select [0]或select .get(0) – steveukx 2012-02-28 07:30:01

+0

哦,是的,当然。谢谢!修复。 – papaiatis 2012-02-28 07:56:58

0

地点选择标签退出循环

 

var selectTag = '<select onchange="document.location.href = this.options[this.selectedIndex].value;">'; 
for(i=0;i<3;i++) { 
selectTag += '<option VALUE="http://www.google.com">'+fStr1[0]+'</option>'; 
} 
selectTag +="</select>" 
othercompaniesli.innerHTML = selectTag; 
 
0

你在做什么是你结束你的选择标记的循环中,所以每一个元素都会有它自己的选择打开和关闭标签。你只是更新你的innerHTML与新的元素这就是为什么它获得最后一个元素。

var openingTag= '<select onchange="document.location.href = this.options[this.selectedIndex].value;">'; 

for(i=0;i<3;i++) 
{ 
    openingTag+= '<option VALUE="http://www.google.com">'+fStr1[0]+'</option> '; 
} 

openingTag= '</select>'; 

othercompaniesli.innerHTML = openingTag;