2 回答
TA贡献1799条经验 获得超8个赞
一种方法是使用来过滤jQuery返回的匹配元素。请参阅此示例:.slice
// Get all li elements
const elements = jQuery("li");
// select the element we need
const el = jQuery("#topic_11");
// get index of the element
const idx = elements.index(el);
// get previous by slicing from the previous index (-1)
const prevElement = elements.slice(idx - 1, idx);
if (prevElement.length == 0)
console.log("No Previous Element");
if (prevElement.length > 0)
console.log(prevElement[0], prevElement.attr("id"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol class="list-group list-group-root sortable">
<li id="topic_13">
<div>
<div>
<span>Web Development</span>
</div>
</div>
<ol>
<li id="topic_1">
<div>
<div>
<span>HTML</span>
</div>
</div>
</li>
<li id="topic_5">
<div>
<div>
<span>CSS</span>
</div>
</div>
<ol>
<li id="topic_3">
<div>
<div>
<span>Frameworks</span>
</div>
</div>
<ol>
<li id="topic_11">
<div>
<div>
<span>Bootstrap 4</span>
</div>
</div>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li id="topic_2">
<div>
<div>
<span>Django</span>
</div>
</div>
</li>
<li id="topic_17">
<div>
<div>
<span>jQuery</span>
</div>
</div>
</li>
</ol>
TA贡献1829条经验 获得超7个赞
您可以在页面上创建所有跨度的集合。单击某个范围时,在集合中找到该范围的索引,然后在集合中引用该索引以访问上一个范围:index - 1
const spans = [...document.querySelectorAll('span')];
spans.forEach((span, i) => {
span.addEventListener('click', (e) => {
console.log(spans[i - 1]);
});
});
<ol class="list-group list-group-root sortable">
<li id="topic_13">
<div>
<div>
<span>Web Development</span>
</div>
</div>
<ol>
<li id="topic_1">
<div>
<div>
<span>HTML</span>
</div>
</div>
</li>
<li id="topic_5">
<div>
<div>
<span>CSS</span>
</div>
</div>
<ol>
<li id="topic_3">
<div>
<div>
<span>Frameworks</span>
</div>
</div>
<ol>
<li id="topic_11">
<div>
<div>
<span>Bootstrap 4</span>
</div>
</div>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li id="topic_2">
<div>
<div>
<span>Django</span>
</div>
</div>
</li>
<li id="topic_17">
<div>
<div>
<span>jQuery</span>
</div>
</div>
</li>
</ol>
spans[i - 1]当然,会给你。如果要导航到其包含 ,请检查范围是否存在,如果存在,请执行 。<span><li>.closest('li')
添加回答
举报