【问题标题】:How to select elements between two "h2" except one element using jquery?如何使用 jquery 在两个“h2”之间选择元素,但一个元素除外?
【发布时间】:2016-10-11 19:38:46
【问题描述】:

所以我正在使用这样设计的网站:

<h2>
  <span id="Explanation"> Explanation </span>
</h2>
<table> ... don't select anything in this table </table>
<a href="https://www.google.com/">hey</a>
<p> What's up? </p>
<p> How's life? </p>
<h2>
  <span id="Transcript"> Transcript </span>
</h2>
<p> Don't select this </p>

我想使用 jQuery 选择解释标题和脚本标题之间的所有内容,但我无法获取任何文本。我目前得到这个的jQuery如下:

explanation = "";
explanation = $("h2 #Explanation").nextUntil("h2 #Transcript").text();

但现在,我根本没有选择任何文本。另外,我不确定如何只获取 a 和 p 文本而不是表格文本。各位大侠有什么帮助,不胜感激,谢谢!

【问题讨论】:

    标签: javascript jquery html selector nextuntil


    【解决方案1】:

    您需要使用:has() 选择器来选择h2 具有特定子级,并使用.not() 从选择器集中删除特定元素。

    $("h2:has(#Explanation)").nextUntil("h2:has(#Transcript)").not("table").text();
    

    var explanation = $("h2:has(#Explanation)").nextUntil("h2:has(#Transcript)").not("table").text();
    console.log(explanation);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h2>
      <span id="Explanation"> Explanation </span>
    </h2>
    <table><tr><td>table</td></tr></table>
    <a href="https://www.google.com/">hey</a>
    <p> What's up? </p>
    <p> How's life? </p>
    <h2>
      <span id="Transcript"> Transcript </span>
    </h2>
    <p> Don't select this </p>

    【讨论】:

    • @Musa Nope,.nextUntil() 返回选定元素并 .not() 过滤它们。
    【解决方案2】:

    以下不包括表格并映射到数组每个元素的文本,以便您可以分隔每个文本块。如果元素中没有空格,则在整个集合上运行 text() 将不会留下任何分隔

    var txt = $('#Explanation').parent().nextUntil('h2:has(#Transcript)').not('table').map(function() {
      return $(this).text()
    }).get().join(' || ')
    
    alert(txt)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h2><span id="Explanation"> Explanation </span></h2>
    <table>
      <tr>
        <td>... don't select anything in this table</td>
      </tr>
    </table>
    <a href="https://www.google.com/">hey</a>
    <p>What's up?</p>
    <p>How's life?</p>
    <h2>
       <span id="Transcript"> Transcript </span>
     </h2>
    <p>Don't select this</p>

    join() 中使用" || " 分隔符只是为了让分隔符在哪里变得明显......相应地调整

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 2017-07-23
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      相关资源
      最近更新 更多