简体   繁体   English

如何计算数量 <li> 使用Javascript通过ajax返回?

[英]How to count the number of <li> returned through ajax using Javascript?

I have a ajax code which returns the list items as 我有一个ajax代码,它返回列表项

<li>one</li>
<li>Two</li>

Each time it will return different number of <li> 's. 每次返回不同数量的<li> I want to check the number of <li> it returns. 我想检查它返回的<li>的数量。 How to check it using Javascript. 如何使用Javascript检查它。 Please Help. 请帮忙。

Here ya go: 你走了:

$(returnedHTML).find('li').length

This takes the returnedHTML and only counts the line items within it. 这将获取返回的HTML并仅计算其中的行项目。

ajaxHtml.split('<li').length - 1 for counting the raw ajax html. ajaxHtml.split('<li').length - 1用于计算原始ajax html。

Or, element.getElementsByTagName("li").length (with element being a parent container for the LI tags.) 或者, element.getElementsByTagName("li").lengthelementLI标记的父容器。)

Have you tried: 你有没有尝试过:

var elements = document.getElementsByTagName('li');
var count = elements.length;

If you need to look within a specific list, jQuery makes it simple: 如果你需要查看特定的列表,jQuery使它变得简单:

$("DIV_NAME > ul > li").length $(“DIV_NAME> ul> li”)。长度

If the list you want to test is coming in as a string from an AJAX request, you'll just treat it like a string, instead of a set of DOM objects. 如果要测试的列表是从AJAX请求中作为字符串输入的,那么您只需将其视为字符串,而不是一组DOM对象。

Take a look at this bit of code. 看看这段代码。

var input = "<li>one</li><li>Two</li>";
var pattern = /<li>/gi;

var match;
var count = 0;
while(match = pattern.exec(input)) {
    count++;
}

alert("There are "+count+" occurences of <li> in the input string.");

What I'm doing here is using an regular expression to find occurrences of <li> case insensitively (just to be certain) and globally (treat the entire string as a single block of text to be searched). 我在这里做的是使用正则表达式来查找<li>不区分大小写(只是为了确定)和全局(将整个字符串视为要搜索的单个文本块)。

FIXED: Some people thought that I am counting LIs on link click event and also not counting it from html response. 修复:有些人认为我在链接点击事件上计算LI,也不计算html响应。 Here is the edited answer. 这是编辑的答案。

If you got html response something like this: 如果你得到这样的html响应:

myhtml.html: myhtml.html:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

Then your jQuery part may be look like this: 然后你的jQuery部分可能如下所示:

$.get('myhtml.html', function(data) {
   alert( $(data).find("li").length ); // 3
});

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

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