我正在使用以下脚本:
$.ajax({
url: urls.notifications,
type: 'POST',
dataType: 'html',
data: {timestamp: notification_timestamp},
success: function(response) {
var responseAmt = $(response).find("li").length;
alert(responseAmt);
}
});
这是我得到的回复:
<li class="notification" data-notification-id="117">
<a href="http://local.dev/user/admin">
<div class="avatar-container">
<img src="http://www.gravatar.com/avatar/64e1b8d34f425d19e1ee2ea7236d3028">
</div>
</a>
<div class="content">
<p class="message">
<a href="http://local.dev/user/admin"><b>admin</b></a> has commented on your post.
<a href="http://local.dev/gag/image-example-10">
<b>Check it out</b>!
</a>
</p>
<p class="timestamp">
<i class="fa fa-clock-o fa-fw"></i>
5 seconds ago </p>
</div>
</li>
每个响应可以包含 1 个或多个 <li>
就是这样,我需要统计一下才能更新responseAmt
变量,保存返回的通知数量。
我尝试过:
$(response).find("li").size(); //shows 0
$(response).find("li").length; //shows 0
但是这个可以正常工作:
$(response).find(".content").length; //shows correct amount
谁知道我为什么不会数<li>
的?
最佳答案
li
元素似乎是选定的节点。 .find
在这些节点内部进行搜索。 IE。 $(response).find("li")
搜索 li
这些 li
中的元素元素(不存在)。
您可以使用 .filter
相反,但如果知道响应中的顶级节点始终是 li
无论如何,只需访问 .length
直接:
$(response).length
关于jquery - <li >'s on the ajax response doesn' t 由于某种原因计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22138760/