【问题标题】:Get text without certain element included using JQuery [duplicate]使用JQuery获取不包含某些元素的文本[重复]
【发布时间】:2021-08-21 14:41:33
【问题描述】:

所以我在下面有这张表。我想在 td.am-r​​eceipt-price 中获取文本,但不包含跨度文本。

<table>
  <tbody>
    <tr>
      <td class="am-receipt-price">
        <span class="am-receipt-discounted-price"><del>price 1</del></span>
        price 2
      </td>
    </tr>
  </tbody>
</table>

console.log ( $(".am-receipt-price").text() ) 也会返回范围内的文本。我试过.remove("span"),但是不行。

我是否遗漏了任何我尚未尝试过的选择器?提前致谢。

【问题讨论】:

  • 同意@Drdilyor,看起来他们所链接的问题的公认答案应该非常适合您的情况

标签: javascript jquery


【解决方案1】:

已经提供的.contents() 解决方案的替代方案(如果您需要/想要替代方案)是使用.clone().remove(),您可以将html 复制到一个变量中,然后您可以用它做您想做的事情不改变原件。

var price = $("td.am-receipt-price").clone();
price.find("span").remove();
console.log(price.text().trim())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td class="am-receipt-price">
        <span class="am-receipt-discounted-price">
          <del>price 1</del>
        </span> 
        price 2
      </td>
    </tr>
  </tbody>
</table>

可能是您的.remove("span") 语法错误:

$("td.am-receipt-price").find("span").remove()

会改变原来的 DOM 节点。

【讨论】:

    【解决方案2】:

    最简单的解决方案是在目标节点周围添加另一个元素并使用选择器来检索它。

    假设您无法修改 HTML,那么您可以在父节点 td 上使用 contents()filter() 来定位节点并读取其 textContent

    let $td = $('.am-receipt-price');
    let nodes = $td.contents().filter((i, n) => n.nodeType === Node.TEXT_NODE && n.textContent.trim() !== '');
    
    console.log(nodes[0].textContent.trim());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tbody>
        <tr>
          <td class="am-receipt-price">
            <span class="am-receipt-discounted-price">
              <del>price 1</del>
            </span> 
            price 2
          </td>
        </tr>
      </tbody>
    </table>

    【讨论】:

    • 我还发现这个脚本也可以使用 $(this) .clone() .children() .remove() .end() .text();
    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2012-03-27
    • 2020-09-27
    • 2023-03-16
    • 1970-01-01
    • 2019-01-12
    • 2022-01-20
    相关资源
    最近更新 更多