选择的Javascript项方法

选择的Javascript项方法,javascript,Javascript,HTML: 这里我们得到了选项的文本。 两者的区别是什么 var x=document.getElementById("mySelect"); alert(x.options.item(1).text); alert(x.options[1].text); 及 因为两者都产生相同的结果。选择元素有一组选项 当您执行选项[i]时,实际上是直接访问集合(例如数组) 当您执行options.item(i)时,您正在通过API访问相同的内容 建议使用第二种方法,因为如果集合的底层实现发生更改,则可能会

HTML:

这里我们得到了选项的文本。 两者的区别是什么

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


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

选择元素有一组选项

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

当您执行options.item(i)时,您正在通过API访问相同的内容

建议使用第二种方法,因为如果集合的底层实现发生更改,则可能会出现异常。这就是为什么有一个API

API规范:
选项集合
返回下拉列表中所有
选项的
集合

x.options[1].text
因此
.text
在这两种情况下都将返回相同的值

以下是收集方法列表选择选项收集

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)

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

  • 长度
  • 项目(索引)
  • namedItem(名称)
除此之外,它还可以作为数组取消引用,即
options[i]
options.item(i)
相同。同样的技巧也适用于像和朋友这样的方法。

类似的问题
x.options[1].text
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)
[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