如何在 querySelectorAll 上使用 JavaScript 触发点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31569890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:50:47  来源:igfitidea点击:

How to trigger click event using JavaScript on querySelectorAll

javascripthtml

提问by Jagan K

In jQuery i have the following code

在 jQuery 我有以下代码

$("li#credit").trigger('click');

This code triggers the click event only on li that has id credit.

此代码仅在具有 id 信用的 li 上触发点击事件。

Now to do this using JavaScript

现在使用 JavaScript 执行此操作

document.querySelectorAll("li#credit").click();

I am getting the error:

我收到错误:

click() is not a function

click() 不是函数

The page I am working have multiple elements with id "credit", I need to trigger a click event only on <li>that has id credit.

我正在工作的页面有多个元素,id 为“credit”,我只需要在<li>具有 id credit 的元素上触发点击事件。

回答by Tasos K.

querySelectorAllreturns a NodeList object (source) and not a DOM element. A NodeList object contains DOM elements.

querySelectorAll返回一个 NodeList 对象(source)而不是一个 DOM 元素。NodeList 对象包含 DOM 元素。

Your code needs to change to get the first element and then call click():

您的代码需要更改以获取第一个元素,然后调用click()

document.querySelectorAll("li#credit")[0].click();

If you want to trigger the .click()event to all elements you can do a forloop

如果你想触发.click()所有元素的事件,你可以做一个for循环

for(var i = 0; i<elems.length; i++) {
    elems[i].click();
}

回答by fangzhzh

I found this one is clean and simple.

我发现这个很干净很简单。

Array.from(document.querySelectorAll("ali#credit")).forEach(button=>button.click())

from this site: https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/#comment-1602558

从这个网站:https: //css-tricks.com/snippets/javascript/loop-queryselectorall-matches/#comment-1602558