<李>的对Ajax响应不计因某些原因 [英] <li>'s on the ajax response doesn't count for some reason

查看:135
本文介绍了<李>的对Ajax响应不计因某些原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的脚本:

$.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个或多个&LT;李&GT; 的那样,我需要算来更新 responseAmt 变量,它包含通知的款额退还。

Each response can contain 1 or many <li>'s like that, and I need to count them to update responseAmt variable, which holds the amount of notifications returned.

我想:

$(response).find("li").size(); //shows 0
$(response).find("li").length; //shows 0

但这一次正常工作:

But this one works correctly:

$(response).find(".content").length; //shows correct amount

任何人都知道,为什么我不能指望&LT;李&GT;

推荐答案

元素似乎是在选择节点。 .find 搜索的节点。即 $(响应).find(礼)搜索里面的锂元素元素(不存在)。

The li elements seem to be the selected nodes. .find searches inside those nodes. I.e. $(response).find("li") searches for li elements inside those li elements (which don't exist).

您可以使用 .filter 代替,但如果知道在响应中的顶级节点总是会元素,无论如何,刚刚接触 .length 直接:

You can use .filter instead, but if know that the top level nodes in the response are always going to be li elements anyway, just access .length directly:

$(response).length

这篇关于&LT;李&GT;的对Ajax响应不计因某些原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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