Sak*_*rda 16 html javascript css-selectors
我正在为我的网站创建一个函数,我在其中设置了一个数据属性,其中包含该元素的第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>
Run Code Online (Sandbox Code Playgroud)
到目前为止我的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;
}
Run Code Online (Sandbox Code Playgroud)
如何使用纯JavaScript(而不是jQuery)获取元素的第n个子编号,这在JavaScript中是否可行?
在这里查看以前的答案.
它用
var i = 0;
while( (child = child.previousSibling) != null )
i++;
//at the end i will contain the index.
Run Code Online (Sandbox Code Playgroud)
当你说“数字”时,你的意思是1、2等还是“一”、“二”等?
如果是 1、2 等等,那么这个数字就是 i+1...
如果是“一”、“二”等,那么您需要获取元素内的文本,然后可能使用正则表达式来解析它并获取您想要的值。
| 归档时间: |
|
| 查看次数: |
50954 次 |
| 最近记录: |