簡體   English   中英

在 DOM 中遍歷跟隨軸

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM