2
 HTML PART
 <select id="carlist" name="cars">
 <option value="volvo">Volvo</option>
 <option value="fiat">Fiat</option>
 <option value="audi">Audi</option>
 </select>


 JAVASCRIPT PART
 cars=["volvo","fiat","audi"];
 var best = "fiat";
 for (var i=0;i<cars.length;i++)
 {
 if (cars.value == best.value)
 (
  document.getElementById('carlist').selectedIndex= 2;
  }

下拉的最终结果总是 audi 因为最后一行中的 .selectIndex 为 2。我在最后一行做了哪些更改,以便下拉列表的值根据变量“最佳”更改?

4

2 回答 2

4
cars=["volvo","fiat","audi"];
var best = "audi";
for (var i=0;i<cars.length;i++)
{
  if (cars[i] == best)
  {
    document.getElementById('carlist').selectedIndex= i;
  }
}

JS小提琴

于 2013-04-24T12:18:17.587 回答
1

尝试这个

  var selectobject=document.getElementById("carlist")
    for (var i=0; i<selectobject.length; i++){
    if(selectobject.options[i].value == best)
         ocument.getElementById('carlist').selectedIndex= i;
    }
    } 

在for循环中写这个逻辑

或者

cars=["volvo","fiat","audi"];
 var best = "fiat";
 for (var i=0;i<cars.length;i++)
     if (cars[i] == best)
       document.getElementById('carlist').selectedIndex= i;
于 2013-04-24T12:18:13.150 回答