遍历DOM .index().eq()中的跟随轴

问题描述 投票:2回答:3

这是一个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>
javascript dom
3个回答
1
投票

通过最初检索所有ps,您可以检查集合中单击元素(.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开始的新集合,filterping,并检查第一个匹配元素:

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>

1
投票

.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>

0
投票
$ ("p.click").click(function () {
target = $(this).nextAll("p.target").first() // following-->nextAll
});

Here is your playground

© www.soinside.com 2019 - 2024. All rights reserved.