【发布时间】:2018-03-22 13:57:18
【问题描述】:
我正在为我的网站创建一个函数,在该函数中我设置了一个包含该元素的第 n 个子编号的数据属性。
我的 HTML 标记:
<html>
<body>
<section class="hardware">some text, nth-child is one</section>
<section class="hardware">some text, nth-child is two</section>
<section class="hardware">some text, nth-child is three</section>
<section class="hardware">some text, nth-child is four</section>
<section class="hardware">some text, nth-child is five</section>
</body>
</html>
到目前为止我的 JavaScript:
var selector = document.getElementsByClassName('hardware');
for(var i = 0; i <= selector.length; i++) {
var index = selector[i] //get the nth-child number here
selector[i].dataset.number = index;
}
如何使用纯 JavaScript(不是 jQuery)获取元素的第 n 个子编号,这在 JavaScript 中是否可行?
【问题讨论】:
-
那是纯javascript不?
-
@bitoiu 是的,但是我怎样才能得到第 n 个孩子的号码?
-
如果可以使用 jQuery,也可以不使用。请记住,jQuery 只是一组 JS 函数。它使事情变得更容易,它不会添加额外的功能。
-
为什么要将“
[object HTMLElement]”设置为data-number值? (selector[i].dataset.number = index;)?
标签: javascript html css-selectors