【问题标题】:Pure JS: Store list of data- attributes in array, then iterate纯 JS:将数据属性列表存储在数组中,然后迭代
【发布时间】:2018-09-29 22:02:58
【问题描述】:

我是 JS 的新手,我可以手动进行 DOM 操作和 if/else 语句。现在我正在尝试一些不合我意的东西,将迭代与数组结合起来,但我有点难以理解它们。

考虑到这一点:考虑到这个 div:<div id="firstAnchor"> 将充当此链接的锚点:<a href="#firstAnchor"></a>

我想存储这些 div 的 ID(id 应该可以是任何东西):

<div id="firstAnchor" style="display: inline-block;">First title</div>
<div id="secondAnchor" style="display: inline-block;">Second title</div>
<div id="thirdAnchor" style="display: inline-block;">Third title</div>

放入一个数组,然后自动创建这三个链接*放置在一个名为“anchorLinks”的div中:

<a href="#firstAnchor">Link to first title</a>
<a href="#seconAnchor">Link to second title</a>
<a href="#thirdAnchor">Link to third title</a>

我该怎么做呢?

* 例如在这个函数中:

(function create_anchor_link_list() {
 //placed here
})();

编辑

这是我尝试开始的内容。我首先在我的 div 元素上使用了data-anchor="firstAnchor" 等,直到我意识到我无法基于data- 属性值链接到 div 元素。所以我尝试了data- 属性:

(function anchorsInPage2(attrib) {
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
    console.log("=#=#=#=#=# anchorsInPage2 function #=#=#=#=#");
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
    console.log("                                            ");

    var elements = document.getElementsByTagName("*");
    var foundelements = [];

    for (var i = 0; i < elements.length; i++) {
        if (elements[i].attributes.length > 0) {
            for (var x = 0; x < elements[i].attributes.length; x++) {
                if (elements[i].attributes[x].name === attrib) {
                    foundelements.push(elements[i]);
                }
            }
        }
    }
    return foundelements;

    console.log("                                              ");
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
    console.log("=#=#=#=#=# / anchorsInPage2 function #=#=#=#=#");
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
})();







function anchorsInPage3() {
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
    console.log("=#=#=#=#=# anchorsInPage3 function #=#=#=#=#");
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
    console.log("                                            ");

    var elements = document.getElementsByTagName("*");
    var foundelements = [];

    for (var i = 0; i < elements.length; i++) {
        if (elements[i].attributes.length > 0) {
            for (var x = 0; x < elements[i].attributes.length; x++) {
                if (elements[i].attributes[x].name === "anchor") {
                    foundelements.push(elements[i]);
                }
            }
        }
    }
    return foundelements;

    console.log("                                              ");
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
    console.log("=#=#=#=#=# / anchorsInPage3 function #=#=#=#=#");
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
}





(function anchorsInPage1() {
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
    console.log("=#=#=#=#=# anchorsInPage1 function #=#=#=#=#");
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
    console.log("                                            ");

    var anchors = document.querySelectorAll('[anchor]');

    for(var i in anchors){
        console.log(i);
    }

    console.log("                                              ");
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
    console.log("=#=#=#=#=# / anchorsInPage1 function #=#=#=#=#");
    console.log("=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#");
})();

进一步测试后首次更新:

使用了 Barmar 的例子。下面的文字是对 Barmar 的直接回答(对于其他评论字段来说太长了)

测试: http://jsfiddle.net/e5u03g4p/5/

我的回复:

使用第一个变量,您找到所有具有属性data-anchor 的元素,所以我猜querySelectorAll 中的括号告诉它我们指的是哪个特定属性,而不是我们想要的元素ID,这是“标准”写作@ 987654337@ 而不是 document.querySelectorAll("[attributeName]")

使用第二个变量,您可以找到 ID 为 anchorLinks 的第一个元素。需要标签来指定 ID,因为querySelector 代表div 所以结果是div#anchorLinks(?)。

然后,您获取变量 anchors(这会导致具有 data-anchor 属性的 div 的 data-anchor 值的数组),对于每个变量,一个函数会触发其中的 d 参数函数等于具有data-anchor 属性的元素的元素ID。对于每个具有data-anchor 属性(即variable anchors)的元素,此函数中的所有内容都会重复。

函数中发生的事情是:

-您创建一个变量 (a),其中包含 &lt;a&gt; 元素的元素创建

-然后将新创建的&lt;a&gt; 元素的href 属性设置为ID 的data-anchor 元素。

-然后我将&lt;a&gt;元素的属性title分配给data-anchor元素的内容(而不是原来的想法textContent被设置为&lt;a&gt;元素`as我希望链接是图像而不是文本)

-然后我还向&lt;a&gt; 元素添加了一个新的class 属性以设置它们的样式

【问题讨论】:

  • StackOverflow 不是免费的编码服务。 SO希望您try to solve your own problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
  • 我们希望通过指出您做错了什么以及如何解决它来帮助您学习。如果你不展示你的尝试,我们怎么能做到这一点?
  • 而不是循环检查所有属性检查attributes[x].name == "anchor",只需调用elements[i].getAttribute("anchor") 并查看它是否返回结果。
  • 您是否要查找以Anchor 结尾的ID,例如firstAnchorsecondAnchor 等?
  • 你可以使用if (element[x].id.test(/Anchor$/))

标签: javascript arrays iteration


【解决方案1】:

如果你在 DIV 中使用了data-anchor="something",那么你应该使用

var anchors = document.querySelectorAll('[data-anchor]');

不是[anchor]

然后您可以使用 forEach() 循环遍历它们

var anchorLinks = document.querySelector("#anchorLinks");
anchors.forEach(function(d) {
    var a = document.createElement('a');
    a.href = '#' + d.id;
    a.textContent = 'Link to ' + d.textContent.toLowerCase();
    anchorLinks.appendChild(a);
});

【讨论】:

  • 感谢您的回复。我刚刚患上了严重的偏头痛(实际上与此无关)。我会尽快检查一下,看看我能做些什么,然后回复你!
  • 将此标记为解决方案,因为它是我得到最终结果的原因。请将最终结果与此进行比较,并阅读我在原始帖子中的最终 cmets 以了解我修改了什么以及为什么。
  • 如果您的最终结果可以满足您的所有需求,您应该将其作为答案发布并接受,而不是将细节放在问题中。
  • 答案应该张贴在这里,而不是第三方网站。
【解决方案2】:

如果您正确设计查询选择器,您可以一次获取所有“锚”元素,然后遍历它们以添加相关链接。

var links = document.getElementById('anchorLinks');
document.querySelectorAll('#anchors div[id]').forEach(function(anchor) {
    var link = document.createElement('a');
    link.href = '#' + anchor.id;
    link.textContent = 'Link for ' + anchor.textContent;
    links.appendChild(link);
});
<div id="anchors">
  <div id="firstAnchor" style="display: inline-block;">First title</div>
  <div id="secondAnchor" style="display: inline-block;">Second title</div>
  <div id="thirdAnchor" style="display: inline-block;">Third title</div>
</div>
<div id="anchorLinks">
</div>

【讨论】:

  • 感谢您的回复。我刚刚被严重的偏头痛击中(字面意思与此无关)。我会尽快检查一下,看看我能做些什么,然后回复你!
  • 你好!看起来有点像 Barmar 的示例,虽然我不理解 .forEach 作为 querySelectorAll 的插件,我不明白将“#anchors div[id]”放入其中意味着什么。你能详细说明那里的语法吗?其余的我都明白。
  • document.querySelectorAll 返回一个可迭代类型,forEach 方法接受一个为可迭代的每个元素调用的回调。选择器#anchors 查找id 为“anchors”的元素,选择器div[id] 查找具有id 属性的div 元素,将它们放在一起,它会查找所有具有id 的div 元素,它们是一个元素的子元素id“锚点”。
  • 啊。你解释得非常好。谢谢! ^^
【解决方案3】:

这个怎么样:

document.getElementsByTagName('div').forEach(function(d) {
    var a = document.createElement('a');
    a.setAttribute('href', '#' + d.id);
    a.innerHTML = 'Link to ' + d.textContent.toLowerCase();
    document.getElementById('anchorLinks').appendChild(a);
});

或者如果你有更多的 div(当然)并且它们有一个特定的类,你可以这样做:

document.getElementsByClassName('your-class-name').forEach(function(d) {
    var a = document.createElement('a');
    a.setAttribute('href', '#' + d.id);
    a.innerHTML = 'Link to ' + d.textContent.toLowerCase();
    document.getElementById('anchorLinks').appendChild(a);
});

【讨论】:

  • 感谢您的回复。我刚刚患上了严重的偏头痛(实际上与此无关)。我会尽快检查一下,看看我能做些什么,然后回复你!
  • 您好!这是一个很好的示例,只要示例中的 div 是我页面中唯一的 div。但是,我已经了解(主要是,我认为)如何解决这个问题。我赞成这个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多