计算jquery中存储在变量内的span数

时间:2015-07-14 08:23:07

标签: javascript jquery

基本上尝试计算items变量中存储的跨度数,但length始终返回0

var items = '<br><span class="holiday">Buddha Jayanti</span><br><span class="workingDay">Shiva Ratri</span>';

var length = $(items).find('span').length;
alert(length); //returning 0

我在这里找不到什么东西?

1 个答案:

答案 0 :(得分:3)

由于span位于元素集的根部,因此.find()不会返回任何元素,因此您需要使用.filter()而不是

var items = '<br><span class="holiday">Buddha Jayanti</span><br><span class="workingDay">Shiva Ratri</span>';

var length = $(items).filter('span').length;
snippet.log(length);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

如果有可能还有后代span元素,那么另一个选项是

var items = '<br><span class="holiday">Buddha Jayanti</span><br><span class="workingDay">Shiva Ratri</span><div><br><span class="workingDay">some value</span></div>';

var length = $('<div />', {
  html: items
}).find('span').length;
snippet.log(length);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>