这类事情应该在服务器端完成,以限制客户端用于此类琐碎任务的资源量。话虽如此,如果您要在前端执行此操作,我建议您考虑使用 underscore.js 之类的东西来保持代码简洁:
var values = ["Red", "Green"],
colors = document.getElementById("colors");
_.each(colors.options, function (option) {
option.selected = ~_.indexOf(values, option.text);
});
如果你使用 jQuery,它可能会更简洁:
var values = ["Red", "Green"];
$("#colors option").prop("selected", function () {
return ~$.inArray(this.text, values);
});
如果您要在没有 underscore.js 或 jQuery 之类的工具的情况下执行此操作,您将需要编写更多内容,并且可能会发现它有点复杂:
var color, i, j,
values = ["Red", "Green"],
options = document.getElementById("colors").options;
for ( i = 0; i < values.length; i++ ) {
for ( j = 0, color = values[i]; j < options.length; j++ ) {
options[j].selected = options[j].selected || color === options[j].text;
}
}