基本上试图计算存储在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
我在这里有什么想念的吗?
最佳答案
因为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>
关于javascript - 计算jquery中变量内部存储的跨度数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31401459/