这是一个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
类按下的是什么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
。然后,访问index + 1
集合中的p
:
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>
s之一,则可以通过构造HTML中所有元素的集合,查找集合中单击元素的索引,构建一个类似的方法。从index + 1
开始的新集合,filter
的p
ing,并检查第一个匹配元素:
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()
假设每个.error
都有一个.click
,我们可以:
.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
});