0

出于某种原因,我很难在选择下拉列表中使用选项的值。这是代码:

<select id="select_category" name="select_category">
  <option value=""></option>
  <option value="home">Home</option>
  <option value="office">Office</option>
  <option value="dinning_room">Dinning Room</option>
</select>

<script>
var select_category = document.getElementById("select_category");
select_category.options["home"].selected = true;
</script>

当我运行它时,我收到错误“无法设置未定义的属性'selected'。如果我在最后一行将[“home”]替换为[2],它可以工作。为什么我不能通过我分配的值引用该选项给它?

谢谢

编辑 - 按照建议,将 javascript 更改为下面的内容,但现在我收到错误“token ILLEGAL”

document.getElementById('select_category').value = 'home';​​​​​​​​​​
4

4 回答 4

3
document.getElementById('select_category').value = 'home';​​​​​​​​​​

jsFiddle Demo

于 2013-07-26T17:37:30.413 回答
2
select_category.options["home"].selected = true;

This line isn't working because options requires an index (ie the number, as you discovered above).

http://www.w3schools.com/jsref/coll_select_options.asp

Give each option a name and use this:

select_category.options.namedItem("nameGoesHere").selected = true;

Alternatively, you can give each option an id and use:

document.getElementById("home").selected = true;

(assuming the id of the option is "home" in this case.

于 2013-07-26T17:37:46.117 回答
1
于 2013-07-26T17:37:29.547 回答
1

因为 options 是一个数组。不过,您可以编写这样的函数:

function selectOptionByValue (select, value) {
    for ( var i = 0; i < select.options.length; i++ ) {
        select.options[i].selected = select.options[i].value === value;
    }
}
于 2013-07-26T17:41:17.877 回答