class JDropSelectRender extends React.Component {
render() {
let items = this.props.options.map((option) => {
if (option.type == 'seperator') {
return (<div style={DropdownSeperatorSty} key={option.key}></div>)
} else {
let selected = Boolean(option.label == this.state.selected.label);
let labelSpanSty = {cursor: 'pointer'};
labelSpanSty.color = selected ? 'green' : 'black';
return (
<div
id='DropdownOptionSty'
key={option.value}
style={DropdownOptionSty}
onMouseDown={this.setValue.bind(this, option)}
onClick={this.setValue.bind(this, option)}
>
<span style={labelSpanSty}>{option.label}</span>
</div>
)
}
});
let value = (<div style={placeSty}>{this.state.selected.label}</div>);
let menu = this.state.isOpen ? <div style={DropdownMenuSty}>{items}</div> : null;
return (
<div id='DropdownSty' style={DropdownSty}>
<div
id='DropdownControlSty'
style={DropdownControlSty}
onMouseDown={this.handleMouseDown}
onTouchEnd={this.handleMouseDown}
>
{value}
<span id='DropdownArrowSty' style={DropdownArrowSty} />
</div>
{menu}
</div>
)
}
}
export default class JDropSelect extends JDropSelectRender {
constructor() {
super();
this.state = { isOpen: false, selected: {} };
}
componentWillMount() {
this.setState({selected: this.props.defaultSelected || { label: 'Select...', value: '' }})
}
componentWillReceiveProps(newProps) {
if (newProps.defaultSelected && newProps.defaultSelected !== this.state.selected) {
this.setState({selected: newProps.defaultSelected});
}
}
handleMouseDown = (event) => {
if (event.type == 'mousedown' && event.button !== 0) return;
event.stopPropagation();
event.preventDefault();
this.setState({ isOpen: !this.state.isOpen })
}
setValue = (option) => {
if (option !== this.state.selected && this.props.onChange) this.props.onChange(this.props.itemName, option);
this.setState({ selected: option, isOpen: false });
}
}
返回控制台中看起来像数组的内容。方括号[]和arr.length = 7.
答案 0 :(得分:7)
从querySelectorAll
返回的对象是NodeList
,它与 一样,但不是实际数组。
尝试将其转换为数组:
[].slice.call(document.querySelectorAll("a[href*='somestring']"));
答案 1 :(得分:3)
HTMLCollection 和 NodeList 对象没有splice
方法,也不会从Array.prototype
继承。
此外,您不能简单地在它们上调用拼接,因为即使它们是类似数组,它们也不会被修改。
首先,将它们转换为真正的数组。
var arr = document.querySelectorAll("a[href*='somestring']"); // NodeList
arr = Array.prototype.slice.call(arr); // Array
arr.splice(2, 2); // splicing an Array
答案 2 :(得分:1)
document.querySelectorAll("a[href*='somestring']")
返回一个不是数组的对象。
尝试将其转换为数组:
var arr = document.querySelectorAll("a[href*='somestring']");
var a = [];
for(var i =0;i<arr.length ; i++){
a[i] = arr[i];
}
a.splice()//now you can use a as an array