如何计算对象内部的元素? [英] How to count elements inside an object?

查看:89
本文介绍了如何计算对象内部的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ajax请求正在返回一个带有HTML的对象,我想计算该对象中的div,只是不知道如何处理.

My ajax request is returning an object with my HTML inside it, I want to count the divs in this object, just can't figure out how.

一些代码:

$.ajax({
 type: "GET",
 url: "/activity_results.html?"+options,
 cache: false,
 success: function(html, status){
 if(html != ""){
 $(html).appendTo("#comments");
 alert(($(html)).length);
}
}
});

在警报中,我正在显示整个HTML对象的长度,但我确实想深入其中并显示一组特定div的长度.

In the alert I am showing the length of the whole HTML object but I want to really be drilling down into it and showing the length of a specific set of divs.

推荐答案

有两种方法可以做到:

$("#comments div").length

或使用context参数:

Or with the context parameter:

$("div", "#comments").length

它们都将为您提供注释中的div数量,但是第二种方法更快.

They'll both give you the number of divs inside comments, but the 2nd method is faster.

如果我了解您要执行的操作,那么上述解决方案似乎可以为您解决.但是存在第三种可能性.如果您已经选择了一个对象并需要查看其中包含多少种某种类型的元素,则情况有所不同.例如,如果您正在使用"this",那么使用上述方法是不切实际的.

If I understand what you're trying to do then it looks like the above solution would work for you. But there is a 3rd possibility. If you've already selected an object and need to see how many elements of a certain type are inside it, then that's a little different. If for example you're working with "this", then it's not practical to use the above method.

相反,您可能会执行以下操作:

Instead you might do something like this:

$(this).find("div").length

或者这仅用于获取立即div的计数:

Or this to get the count of immediate divs only:

$(this).children("div").length

这篇关于如何计算对象内部的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆