从<span> </span> </span>中的<span>获取文本

时间:2014-12-03 08:37:19

标签: javascript jquery html

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

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

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

需要jQuery代码的任何想法吗?

2 个答案:

答案 0 :(得分:2)

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

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

&#13;
&#13;
var text = $(".priceValue > span").first().text();
snippet.log(text);
&#13;
<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>
&#13;
&#13;
&#13;

如果您有多个.priceValue元素并且需要每个元素中的第一个跨度文本,那么它有点棘手:

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

&#13;
&#13;
var textArray = $(".priceValue").map(function() {
  return $(this).children("span").first().text();
  }).get();
snippet.log(textArray.join(", "));
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$("span>span").text(); // direct descendant use this

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