简体   繁体   English

在输出到 HTML 之前计算数据中的列表项

[英]Count list items in data before outputting to HTML

I have a list that is being returned using ajax that looks like this...我有一个使用 ajax 返回的列表,看起来像这样......

console.log(data);

<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>

I am inserting it into a HTML element like this...我将它插入到这样的 HTML 元素中......

$("#output").html(data);

This is working correctly, but I would like to count the number of list items before I output it to the element.这工作正常,但我想在将其输出到元素之前计算列表项的数量。 I have tried the following but it just gives me the count of characters...我已经尝试了以下但它只给了我字符数......

console.log(data.length);

Where am I going wrong?我哪里错了? Is there a way to do this before outputting the HTML?在输出 HTML 之前有没有办法做到这一点?

Your data is just a string, so you can use jQuery to turn it into jquery object and then select li elements from that object and get the length.您的数据只是一个字符串,因此您可以使用 jQuery 将其转换为 jquery 对象,然后从该对象中选择li元素并获取长度。

 const data = '<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>' const html = $(data); console.log(html.find('li').length) $("#output").html(html);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="output"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM