给定一个有序列表<ol> <li id="item">ipsum</li> <li id="other">lorem</li><ol><span>The item <cite src="other?"></cite> is an item.</span>是否可以按序数引用列出的项目?例如如果我写<cite src="other"><cite>,它将显示为Item (2)?我事先不知道它在列表中的位置,因此需要以某种方式自动完成。 CSS可能吗?预期产量:  ipsum  洛雷姆项目2.是项目。本质上,<cite src="other"><cite>应该复制序数值的内容。如果不能通过CSS的当前限制来获得这样的解决方案,那么JavaScript解决方案就足够了。 最佳答案 对于每个<cite>标记,循环遍历<ol>子代,如果找到具有和id属性匹配<cite>的src属性的子代,则将其位置(+1)设置为<cite>的:var cites = document.getElementsByTagName("cite");var listItems = document.getElementById("my-items").children;for(var i = 0; i < cites.length; i++) { var cite = cites[i]; var src = cite.getAttribute("src"); for (var j = 0; j < listItems.length; j++) { var id = listItems[j].getAttribute("id"); if(id === src) { cite.innerText = j + 1; break; } }}<ol id="my-items"> <li id="item">ipsum</li> <li id="other">lorem</li><ol><span>The item <cite src="other"></cite> is an item.</span>编辑:更有效的解决方案:var listItems = document.getElementById("my-items").children;for(var i = 0; i < listItems.length; i++ ) { var id = listItems[i].getAttribute("id"); var cite = document.querySelector("[src='" + id + "']"); if(cite) cite.innerText = i + 1;}<ol id="my-items"> <li id="item">ipsum</li> <li id="other">lorem</li><ol><span>The item <cite src="other"></cite> is an item.</span>关于javascript - 通过其对价引用列出的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42454783/
10-09 14:46