微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么 if 语句没有在 Javascript 的 forEach 函数中运行?

如何解决为什么 if 语句没有在 Javascript 的 forEach 函数中运行?

我一直在研究工具提示,为此我创建了一个 javascript 函数 Tooltip(),其中我选择了所有 DOM 元素,例如 const targets = document.querySelectorAll('*'),在选择了所有元素后,我添加forEach函数targets 变量和内部为每个函数创建了一个 if 语句,在该语句中我检查了一个元素是否包含我在 requiredAttrs 数组中提到的特定属性,但它以某种方式不起作用!而且我不知道我哪里做错了。

完整代码

function Tooltip() {
      const requiredAttrs = ['data-tooltip','data-tooltip-position','data-tooltip-content'];
      const targets = document.querySelectorAll('*');

      targets.forEach((target,index) => {
            if (target.hasAttribute(requiredAttrs[index])) {
                  console.log('Y');
            } else {
                  console.log('No');
            }
      });
}

Tooltip();
<!DOCTYPE html>
<html dir="ltr" lang="en">
      <head>
            <Meta charset="UTF-8" />
            <Meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <Meta name="viewport" content="width=device-width,initial-scale=1.0" />
            <link rel="stylesheet" href="public/css/main.css" />
            <title>Pearl Framework</title>
      </head>
      <body class="vh-full grid-center">
            <style>
                  body {
                        background-color: #a1a1a1;
                  }

                  .Box {
                        width: 100px;
                        height: 100px;
                        background-color: purple;
                  }
            </style>

            <div
                  class="Box"
                  data-tooltip="true"
                  data-tooltip-position="top-center"
                  data-tooltip-content="Hello,World!"
            ></div>

            <script src="public/script/tooltip.js"></script>
      </body>
</html>

如您所见,<div class="Box"></div> 具有全部 3 个属性,因此 if 语句应该运行,但 else 部分正在运行。

解决方法

目标数组的索引与您要比较的 requiredAttrs 数组的索引不对应。你会想要这样的东西:

targets.forEach((target,index) => {
  const hasAttrs = requiredAttrs.every(attr => target.hasAttribute(attr));
  if (hasAttrs) {
    console.log('Y');
  } else {
    console.log('No');
  }
});

编辑:

这是有效的,因为您对 querySelectorAll 的调用实际上是捕获页面上的每个元素并将其作为数组返回。在您的 forEach 调用中,您将使用当前元素的数组索引位置,我们正在检查这些属性是否存在以检查 requiredAttrs。因此,当我们甚至迭代到具有您感兴趣的属性的 div 时,我们可能正在处理一个大于 requiredAttrs 数组长度的索引,更不用说我们只会检查 一个 attrs 而不是全部。我的代码采用目标节点并调用 requiredAttrs 数组上的 .every 方法以检查目标节点上是否存在所需的每一个属性。

虽然这解决了最初的问题,但我应该注意这可能会导致性能不佳,并且不是查找具有特定属性的元素的推荐方法。如果你想要一个元素集合,这些元素都保证在你的数组中具有属性,你可以简单地将它们添加到你的查询中,如下所示:

docmuent.querySelectorAll('*[data-tooltip][data-tooltip-position][data-tooltip-content]');
,

首先,这里使用索引是不正确的,因为它是目标数组的索引, 如果你看一下 document.querySelectorAll('*') 的输出 你可以看到,它还包含了 HTML、head 和其他标签,

换句话说,您正在尝试通过超过其长度的索引访问 requiredAttrs

你必须用 for 循环 arround requiredAttrs 包裹你的 if 语句

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。