Select 标签的 Options 属性 探究

0x00. 缘起

在阅读 《深入 React 技术栈》 的时候 (P59-60), multiple select , 里面提到了 e.target.options 返回是对象,不是数组, 就稍加研究了一番。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
area: ['beijing', 'shanghai'],
};
}
handleChange(e) {
const { options } = e.target;
// 注意,这里返回的 options 是一个对象,并非数组 【yafey注:好奇害死猫--> 这个对象是什么 ? 】
const area = Object.keys(options)
.filter(i => options[i].selected === true)
.map(i => options[i].value);
this.setState({
area,
});
}
render() {
const { area } = this.state;
return (
<select multiple={true} value={area} onChange={this.handleChange}>
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
<option value="hangzhou">杭州</option>
</select>
);
}
}

0x01. 研究过程

e.target.options 挺别致啊,是什么鬼。

无论 在 HTML 元素参考 <select> @ MDN (update : 页面上其实有个 link 的)还是 target Event Property @w3schools.com bootcss 镜像 , 都没有看到过 有 options 属性。

参考了 https://stackoverflow.com/questions/38379328/why-select-option-change-event-cant-have-this-and-event-target-to-get-selected 中的代码, 修改为 multiple select

在 console 里面看到 HTMLOptionsCollection , 这就是 e.target.options.

1498495705372

完整的代码在 jsfiddle 上, 不知道看不看的到。https://jsfiddle.net/mrcbtt6f/10/

再回头到 MDN 上查找 : Web API 接口 HTMLSelectElement

The HTMLSelectElement interface represents a <select> HTML Element. These elements also share all of the properties and methods of other HTML elements via the HTMLElement interface.

HTMLSelectElement.options 只读

Returns a HTMLOptionsCollection containing the set of <option> elements contained by this element.

1498496071032

还有很多其他 的 Properties , 看到这里, 终于理顺了, 也明白了 返回的是一个对象, 不是一个数组是什么意思了。

0x02. 心得

看技术书还是得多思考, 多总结啊。

-------------本文结束感谢您的阅读-------------

本文标题:Select 标签的 Options 属性 探究

文章作者:YaFey

发布时间:2017年06月26日 - 23:06

最后更新:2017年06月27日 - 01:06

原始链接:https://hyf.js.org/blog/2017-06-26.2017-06-event-target-options-of-multiple-select/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

如果我的文章让你有收获,请支持一下!
0%