从<跨度>获取<跨度>内的文本

Getting text from <span> within a <span>

本文关键字:跨度 文本 获取      更新时间:2023-09-26

在我正在使用的html中,有这个近似结构:

...
<span class="priceValue">
  ...
  <span id="asd...">
    12345
  </span>
</span>
...

我想获取第二个(嵌套的)的 *.text() 的数字。问题是我不能使用"id="属性。

需要对jQuery代码有什么想法吗?

如果它是第一个.priceValue元素中的第一个span,则:

var text = $(".priceValue > span").first().text();

var text = $(".priceValue > span").first().text();
snippet.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="priceValue">
  <div>Not me</div>
  <span>One</span>
  <span>Not me</span>
</div>
<div class="priceValue">
  <div>Not me</div>
  <span>Two</span>
  <span>Not me</span>
</div>
<hr>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

如果你有几个.priceValue元素,并且每个元素中都需要第一个跨度的文本,那就有点棘手了:

var textArray = $(".priceValue").map(function() {
  return $(this).children("span").first().text();
  }).get();

var textArray = $(".priceValue").map(function() {
  return $(this).children("span").first().text();
  }).get();
snippet.log(textArray.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="priceValue">
  <div>Not me</div>
  <span>One</span>
  <span>Not me</span>
</div>
<div class="priceValue">
  <div>Not me</div>
  <span>Two</span>
  <span>Not me</span>
</div>
<hr>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

$("span>span").text(); // direct descendant use this
$("span span").text(); // if don't know if next span is direct descendant