js解决元素索引值问题

今天在做评论列表的时候,想要获取某元素的索引,想起来原生js并没有JQuery中的index()函数。

  • 解决方案,为nodelist中每个元素手动添加index属性
/**
 * 为nodelist添加索引
 * @param {NodeList} nodelist 元素集合
 */
function addIndex (nodelist) {
    const len = nodelist.length

    for (let i = 0; i < len; i++) {
        nodelist[i].index = i
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41418386/article/details/80617667