2

HTML:

<select id="mySelect">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
</select>

Javascript:

var x=document.getElementById("mySelect");
alert(x.options.item(1).text);
alert(x.options[1].text);

在这里,我们得到了选项的文本。和有什么区别

x.options.item(1).text

x.options[1].text

因为两者都产生相同的结果。

4

3 回答 3

5

SELECT 元素有一组选项。

当您执行 options[i] 时,您实际上是在直接访问集合(例如数组)。

当您执行 options.item(i) 时,您访问的是相同的东西,但通过 API。

推荐第二种方式,因为如果集合的底层实现发生变化,您可能会遇到异常。这就是为什么有一个API。

API 规范: https ://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionsCollection

于 2013-09-16T07:54:19.970 回答
1

options collection返回下拉列表中的collection所有内容。options

x.options.item(index)       //Returns the element from the collection with the specified index

x.options[index]            // will returns element from collection with specified collection .index is an integer specifies the element to retrieve (starts at 0)

所以.text在这两种情况下都会返回相同的

这是收集方法的列表选择选项收集

[index]                 An integer that specifies the element to retrieve (starts at 0)
[add(element[,index])]  Adds an option element into the collection at the specified index. If no index is specified, it inserts the option element at the end of the collection
item(index)             Returns the element from the collection with the specified index
namedItem(name)         Returns the element from the collection with the specified name (name or id attribute)
remove(index)           Removes the element with the specified index from the collection
于 2013-09-16T07:55:50.200 回答
0

这里的options对象实际上是一个OptionsCollection继承自的实例HTMLCollection;因此,它公开了一些属性和方法,例如:

  • length
  • item(index)
  • namedItem(name)

除此之外,它还可以作为数组取消引用,即options[i]options.item(i). 相同的技巧可以应用于likegetElementsByClassName()和friends 的方法。

于 2013-09-16T07:57:02.110 回答