我有下拉列表的代码
if (chosen == "Parade") {
selbox.options[selbox.options.length] = new Option("Select Venue","");
selbox.options[selbox.options.length] = new Option("Benavides Park","Benavides Park");
selbox.options[selbox.options.length] = new Option("CME Auditorium","CME Auditorium");
selbox.options[selbox.options.length] = new Option("Engineering Sports Complex","Engineering Sports Complex");
selbox.options[selbox.options.length] = new Option("Field in front of Grandstand","Field in front of Grandstand");
selbox.options[selbox.options.length] = new Option("Plaza Mayor","Plaza Mayor");
selbox.options[selbox.options.length] = new Option("Quadricentennial Park","Quadricentennial Park");
selbox.options[selbox.options.length] = new Option("Rectors Hall","Rectors Hall");
selbox.options[selbox.options.length] = new Option("Seminary Gym","Seminary Gym");
selbox.options[selbox.options.length] = new Option("Tinoco Park","Tinoco Park");
selbox.options[selbox.options.length] = new Option("UST Grandstand","UST Grandstand");
selbox.options[selbox.options.length] = new Option("UST Gymnasium","UST Gymnasium");
selbox.options[selbox.options.length] = new Option("Venue not listed/outside UST","Venue not listed/outside UST");
}
选项“Benavides Park”的默认值是什么代码? 在HTML中,它就像这样
selected="selected"
在javascript中怎么样?
答案 0 :(得分:5)
你需要使用
new Option("UST Grandstand","UST Grandstand", 1);
注意右边的1。这意味着选择
答案 1 :(得分:1)
我建议您使代码更清晰,如下所示:
var selectedItem = -1; // change to select different item
var options = ["Benavides Park", "CME Auditorium", "Engineering Sports Complex", "Field in front of Grandstand", "Plaza Mayor", "Quadricentennial Park", "Rectors Hall", "Seminary Gym", "Tinoco Park", "UST Grandstand", "UST Gymnasium", "Venue not listed/outside UST"];
selbox.add( new Option("Select Venue", "", (-1 == selectedItem) ? 1 : 0));
for (var i = 0; i < options.length; i++) {
selbox.add( new Option(options[i], options[i], (i == selectedItem) ? 1 : 0) );
}
对我而言,这感觉更好,因为无论何时想要更改值,您只需更改其在数组中的值。这也可以重构为它自己的函数,只接受一个数组和选择框来加载项目。
(在Chrome中测试但应该在大多数地方都可以使用;你可以在w3schools找到一个黑客来修复IE6。此外,如果选择框中有项目,那么它们将保留。你可能想要清除它首先使用此处的代码:http://www.plus2net.com/javascript_tutorial/list-remove.php)
答案 2 :(得分:0)
试试这个:
var foo = document.getElementById('yourSelect');
if (foo)
{
foo.selectedIndex = 0;
}