【问题标题】:Foreach function that clicks on check boxes单击复选框的 Foreach 函数
【发布时间】:2019-12-07 22:40:21
【问题描述】:

我需要点击一系列复选框的功能。然而,我并不总是知道我是什么。我尝试编写一个 forEach 循环,但它不起作用:

这个 for 循环有效:

function check Boxes() {
  for (let i = 0; i < 249; i++) {
    document.getElementsByClassName("inventoryCbox")[i].click();

  }
}

这是不工作的 for 循环。我想也许我的语法是错误的。

checkBoxes();
var boxes = document.getElementsByClassName("inventoryCbox");

function checkBoxes(node) {
  node.forEach(function(boxes) {
    boxes.click()
  });
}

【问题讨论】:

  • 你的意思是写function check Boxes() {},在“check”和“Boxes”之间有一个空格?我格式化了你的代码,但在我格式化之前就在那里。
  • 还请定义究竟是什么不起作用。
  • 如果下面的任何答案回答了您的问题,Stack Overflow 的工作方式,您可以通过单击旁边的复选标记“接受”该答案; details here.

标签: javascript loops checkbox foreach


【解决方案1】:

这将检查所有具有“inventoryCbox”类的复选框:

document.querySelectorAll(".inventoryCbox").forEach(node =&gt; node.click())

【讨论】:

  • 忘记删除了,谢谢! (不用担心投反对票)
  • 非常感谢您的帮助 - 这很好用..:)
【解决方案2】:

node 在你的checkBoxes 函数中是undefined,因为你没有向函数传递任何东西。此外,您的代码让您调用checkBoxes您将任何内容分配给boxes。您可能打算直接使用boxes

// This *before* `checkboxes`
var boxes = document.getElementsByClassName("inventoryCbox");
checkBoxes();

function checkBoxes() { // <== No parameter
  boxes.forEach(function(box) {
//^^^^^                  ^^^
    box.click()
//  ^^^
  });
}

但这仍然有一个问题:getElementsByClassName 返回的HTMLCollection 没有forEach 可靠地跨浏览器。 (querySelectorAll 返回的 NodeList 在现代浏览器上有它,但在 HTMLCollection 上没有。)

如果你喜欢,可以添加:

if (typeof HTMLCollection !== "undefined" &&
    HTMLCollection.prototype &&
    !HTMLCollection.prototype.forEach) {
    // Yes, direct assignment is fine here, no need for `Object.defineProperty`
    HTMLCollection.prototype.forEach = Array.prototype.forEach;
}

那么上面的更新代码就可以工作了。

或者坚持你现有的循环,或者直接使用Array.prototype.forEach

function checkBoxes() { // <== No parameter
  Array.prototype.forEach.call(boxes, function(box) {
    box.click()
  });
}

My answer here 详细介绍了添加 forEachHTMLCollection 的可迭代性(以及在尚未实现 NodeList 可迭代性的环境中的 NodeList)。

【讨论】:

  • 非常感谢 TJ 抽出时间如此清楚地写出这篇文章。非常感激!我试图投赞成票,但在 Stackoverflow 上还不够活跃。
【解决方案3】:

如果你想点击某个类选择的所有元素,你可以使用这个例子

var els = document.querySelectorAll('.inventoryCbox'); 
for (i = 0; i < els.length; ++i) {
     els[i].click();
};

【讨论】:

    猜你喜欢
    • 2018-02-01
    • 2019-09-28
    • 2016-11-14
    • 2018-03-23
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    相关资源
    最近更新 更多