如何选择并单击所有html复选框? [英] How to select and click all html checkboxes?

查看:52
本文介绍了如何选择并单击所有html复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望选择并点击网页中的所有复选框.我尝试过:

I desire to select and click all checkboxes in a webpage. I've tried:

document.querySelectorAll('button[role="checkbox"]').forEach((e)=>{
    e.click();
});

也:

document.querySelectorAll('[aria-checked="false"]').forEach((e)=>{
    e.click();
});

什么也没有发生,并且devtool控制台输出"undefined".

Nothing happens, and devtool console outputs "undefined".

要重现,您需要具有已删除邮件的hotmail电子邮件帐户.

To reproduce you need to have an hotmail email account with messages already deleted.

在hotmail.com中,转到已删除邮件",在那里恢复已删除邮件",然后将打开一个窗口,其中包含已删除的对话.每个对话附近都会有一个复选框.

In hotmail.com go to "Deleted items", there to "recover deleted items", and then a window will be opened with deleted conversations. Near to each conversation there will be a checkbox.

推荐答案

您在正确的轨道上,但是缺少一些细节.首先,查询选择器功能起作用.寻找元素是他们的面包和黄油.如果未定义,则选择器字符串不正确.您的HTML是否使用<input type="checkbox">来实现复选框?

You're on the right track, but missing a few details. First, the query selector functions work. Finding elements is their bread and butter. If you're getting undefined, then your selector string is not correct. Does your HTML implement check boxes with <input type="checkbox">?

第二,不要使用.click().这可能有效,但对于后续/维护程序员来说,则需要更多的工作和认知上的努力.此外,它还可能触发点击事件(当然,您当然也希望如此).只需设置checked属性:

Second, don't use .click(). That may work, but is more work and cognitive effort for the followup/maintenance programmer. It additionally might trigger click events (unless of course you'd like that too). Just set the checked attribute:

document.querySelectorAll('input[type="checkbox"]').forEach( (e) => e.setAttribute('checked', '') ); 

这篇关于如何选择并单击所有html复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆