基本上尝试计算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
我在这里找不到什么东西?
答案 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>