如何使用从一个div中收集到的数据集ID值来形成一个数组

huangapple go评论65阅读模式
英文:

How to form an array using series of dataset Id values you've collected from a div

问题

数据集ID已附加到图像 假设我已将数据集ID值附加到一系列div中,这些值彼此不同,如果我想收集这些值并将它们组成一个数组,我该如何做?

我已经尝试通过循环遍历它们,因为它们都是具有相同类名的div,但它只会将值返回到单独的数组中,而不是合并到一个数组中。我不能使用array.from(),因为它会将字符串分成单独的字符并形成一个包含它们的数组。你们有什么建议?

英文:

The dataset Id is attached to the imageLet's say for instance I've attached dataset Id values to a series of div's and these values are different from one another, if I want to collect these values and form an array with them how do it do it?

I already tried looping through them since they are all divs with the same class name,but it gives me back the values on individual array and not collectively into one array. I can't use array.from() cos it would just turn the string into separate characters and form an array with them. What do you all suggest I do?

答案1

得分: 1

你可以首先使用document.querySelectorAll按类选择所有元素,然后应用映射函数来读取dataset.id

const res = Array.from(document.querySelectorAll('.a'), d => d.dataset.id);
console.log(res);
<div data-id="100" class="a"></div>
<div data-id="101" class="a"></div>
<div data-id="102" class="a"></div>
英文:

You can first select all the elements by class with document.querySelectorAll, then apply a mapping function to read the dataset.id.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const res = Array.from(document.querySelectorAll(&#39;.a&#39;), d =&gt; d.dataset.id);
console.log(res);

<!-- language: lang-html -->

&lt;div data-id=&quot;100&quot; class=&quot;a&quot;&gt;&lt;/div&gt;
&lt;div data-id=&quot;101&quot; class=&quot;a&quot;&gt;&lt;/div&gt;
&lt;div data-id=&quot;102&quot; class=&quot;a&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月17日 12:29:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定