我需要通过JS中的循环单击事件

我是JavaScript的新手,在我的小型项目中,每次循环迭代时我都需要用户单击一个按钮,但实际上并没有发生。

INPUT: <input id="input" >
<button id="btn">Play</button>

  <script>
        const btn = document.querySelector('#btn');
        const inp = document.querySelector('#input');
        for(let i = 0; i < 10; i++){
            btn.addEventListener('click', function(){
            let x = inp.value;
            console.log(x);
            console.log(i);
});
        }

   </script>

我也尝试了while循环!我该怎么办?请帮忙! 提前致谢。

评论
Lee
Lee

From what I've mentioned in my comment, you're only setting an event listener (with addEventListener) on the button, not clicking the button.

Instead, you should create a new event with the Event constructor, then call EventTarget#dispatchEvent on the element with the event as the argument:

const button = document.getElementById('button');
const input = document.getElementById('input');

for (let i = 0; i < 10; i++) {
  const event = new Event('click');
  button.dispatchEvent(event);
}

(P.S. While you're at it, I suggest that you should use Document#getElementById if you want to retrieve an element by its unique ID instead of Document#querySelector.)

点赞
评论