在 vanilla js 中的多个元素上调用 click() 并做出反应

Calling click() on multiple elements in vanilla js and react

示例: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 循环替换为 for...of 循环:

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>

为了继续我对原始 post 的评论(可能不是完整的答案),我添加了这个答案来演示。

同一程序仅适用于循环绑定更改。

    <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 即可锁定每个元素的作用域,而不仅仅是最后一个元素!