[英]Traverse the following axis in the DOM
这是一个 DOM 片段。
<p class="target">1</ p>
<p class="click"></ p>
<table>
<tr><td><p class="click"></p></td></tr>
</table>
<p class="target">2</p>
我想找到target
类的下一个 p,与click
类按下的 p 是什么 DOM 级别无关。 在 p 值为 2 的情况下
就像是
$ ("p.click").click(function () {
target = $(this).following("p.target").first()
});
但是我找不到如何在 DOM 中遍历跟随轴,除了 xpath 可能不适用于所有浏览器。
如果我什么都不知道那就太好了:)
编辑
我写这个问题不够正确。 更合适的代码如下。 按click
我想得到第一个error
<input class="click" type="button" value="1">
<p class="error"></ p>
<table>
<tr><td><input class="click" type="button" value="2"></td></tr>
</table>
<p class="error"></p>
通过检索所有p
s ^首先,你可以检查.index
单击元素(的this
集合中)。 然后,访问该p
集合中的index + 1
:
const $ps = $('p'); $("p.click").click(function() { const thisPIndex = $ps.index(this); console.log($($ps[thisPIndex + 1]).text()); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p class="target">1</ p> <p class="click"></ p> <table> <tr> <td> <p class="click">click</p> </td> </tr> </table> <p class="target">2</p>
如果被点击的元素不一定是你关心索引的集合中的<p>
之一,你可以按照类似的方法构造一个 HTML 中所有元素的集合,在集合中找到被点击元素的索引,从该index + 1
开始构造一个新集合,通过p
filter
,并检查第一个匹配元素:
const $ps = $('p'); const allElms = $('*'); $(".click").click(function() { const thisElmIndex = allElms.index(this); const followingElements = allElms.slice(thisElmIndex + 1); console.log(followingElements.filter('p')[0].textContent); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input class="click" type="button" value="1"> <p class="error">1</p> <table> <tr> <td><input class="click" type="button" value="2"></td> </tr> </table> <p class="error">2</p>
.index()
& .eq()
假设每个.click
都有一个.error
,我们可以:
.click
.click
相关的已点击.click
索引号.error
找到等效的索引号。演示中评论的详细信息
/* - Register click event on document - Any .click clicked will be $(this) - Get the index number of the clicked button in relation to all .click on the document. - Use the same index number to find the associated .error */ $(document).on('click', '.click', function(e) { var idx = $(this).index('.click'); $('.error').eq(idx).show(); });
.error { display: none }
<input class="click" type="button" value="1"> <p class="error">ERROR 1</ p> <table> <tr> <td><input class="click" type="button" value="2"></td> </tr> </table> <p class="error">ERROR 2</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$ ("p.click").click(function () {
target = $(this).nextAll("p.target").first() // following-->nextAll
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.