如何在原生JavaScript中选中指定索引位置的<li>标签
问题原因
你当前的实现存在两个核心问题:
- 生成
<li>标签时没有绑定索引标识,也没有设置id属性,无法直接通过值匹配找到对应标签 - 直接用数组元素值作为id的逻辑存在缺陷:如果数组有重复值会出现匹配错误,且纯数字id不符合HTML规范
解决方案
你可以直接利用渲染后<li>标签的顺序和原数组索引完全对应的特性,直接从父节点的子元素集合中按索引取值,实现成本最低:
1. 原有showItem函数无需改动,直接用以下代码选中目标标签
var intArr = document.querySelector("input.arrayInput").value.split(" ").map(function (item) { return parseInt(item, 10); }); // 直接从父容器arrValue的子元素中取索引为low的节点 const targetLi = arrValue.children[low]; // 增加边界判断避免索引越界报错 if (targetLi) { targetLi.style.backgroundColor = "#4ac7ee"; targetLi.style.color = "#ffffff"; }
可选优化方案(如果父容器存在其他非
如果arrValue下还有其他无关标签,你可以在渲染时给<li>绑定自定义索引属性,避免匹配错误:
// 修改后的showItem函数 function showItem(intArr){ var newTask = ""; // 遍历的时候带上索引参数 intArr.forEach((element, index)=>{ // 给每个li添加data-index属性存储对应数组索引 newTask+=`<li data-index="${index}">${element}</li>`; }) arrValue.innerHTML = newTask; console.log("item added"); } // 选中逻辑 const targetLi = document.querySelector(`li[data-index="${low}"]`); if (targetLi) { targetLi.style.backgroundColor = "#4ac7ee"; targetLi.style.color = "#ffffff"; }
内容的提问来源于stack exchange,提问作者Ritu Bhangale
相关产品推荐
相关产品推荐

