所以我在下面有这张表。我想在 td.am-receipt-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")
但它不起作用。
我是否遗漏了任何我还没有尝试过的选择器?提前致谢。
答案 0 :(得分:2)
最简单的解决方案是在目标节点周围添加另一个元素并使用选择器来检索它。
假设您无法修改 HTML,那么您可以在父节点 contents()
上使用 filter()
和 td
来定位节点并读取其 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>
答案 1 :(得分:0)
已经提供的 .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 节点。