示例:clearButtons
有两个元素。问题:clearButton.click()
只调用一个元素。它应该完全
此处的代码:https://stackblitz.com/edit/react-6bam4e
import {Typeahead} from 'react-bootstrap-typeahead';
// ES2015
class App extends Component {
constructor() {
super();
this.state = {
items: [{name: 'A'}, {name: 'B'}]
};
}
clearInput = () => {
const clearButtons = document.querySelectorAll(".rbt-token-remove-button");
for (const clearButton of clearButtons) {
clearButton.click();
}
}
render() {
return (
<div>
<Typeahead
id={'example4'}
defaultSelected={this.state.items.slice(0, 3)}
/*disabled = {this.state.selectGroupTasksId === ''}*/
labelKey="name"
multiple
options={this.state.items}
placeholder="Choose ..."
ref={(ref) => this._typeahead = ref}
/>
<button onClick={this.clearInput }>Button</button>
</div>
);
}
}
render(<App />, document.getElementById('root'));
让你的生活更轻松,用for...of
-loop 替换基于索引的 for 循环:
clearInput = () => {
const clearButtons = document.querySelectorAll(".clear-button");
for (const clearButton of clearButtons) {
setTimeout(() => {
clearButton.click();
}, 100);
}
}
clearInput()
<button class="clear-button" onclick="console.log('button 1')">Button 1</button>
<button class="clear-button" onclick="console.log('button 2')">Button 2</button>
为了继续我对原始帖子的评论(可能不是完整的答案(,我添加这个答案来演示。
相同的程序仅适用于循环绑定更改。
<input type="button" class="clear-button" onclick="console.log('1')" value="1" />
<input type="button" class="clear-button" onclick="console.log('2')" value="2" />
<input type="button" class="clear-button" onclick="console.log('3')" value="3" />
<input type="button" class="clear-button" onclick="console.log('4')" value="4" /> <br><br>
<input type="button" onclick="clearInput()" value="clear" />
<script>
clearInput = () => {
const clearButton = document.querySelectorAll(".clear-button");
for (let i = 0; i < clearButton.length; i++) {
setTimeout(() => {
clearButton[i].click();
}, 100);
}
}
</script>
我不知道该按钮上的处理程序是什么,但它有问题。 编辑代码。这个解决方案对我有用。
clearInput = () => {
const clearButtons = document.querySelectorAll(".rbt-token-remove-button");
if (clearButtons.length > 0) {
setTimeout(() => {
clearButtons[0].click();
this.clearInput()
})
}
}
只需将const
替换为let
即可锁定每个元素的范围,而不仅仅是最后一个元素!