【问题标题】:Select every div inside another div and check it's class with jQuery选择另一个 div 中的每个 div 并使用 jQuery 检查它的类
【发布时间】:2014-09-21 05:26:02
【问题描述】:

我有一个聊天系统,我正在使用 jQuery + JSON + PHP 显示消息。我的问题是:我必须选择包含消息的 div“#chatMessages”中的每个 div,并检查它的类以查看它是否存在,我的 Ajax 代码:

    var data = {};
$.ajax({
    type: "GET",
    dataType: "json",
    url: "../room/a.php",
    async: true,
    cache: false,
    data: data,
    success: function(response) {
        if(response.error) {
            alert(response.msg);
        } else {
            for(var i = 0; i < response.length; i ++) {
                if($("#chatScreen > *").hasClass("message" + i) == false)
                $("#chatScreen").append($("<div>",{
                    class : 'message' + response[i][1],
                    html  : response[i][0] + ' ' + response[i][4]
                }));
            }
        }
    },
    error: function (response) {

        },
    complete: function () {

        }
    });

response[i][0] 包含名称,response[i][4] 包含消息。它工作正常,但我每 3000 毫秒加载一次此函数,因此它重复每条消息,我如何检查每个 div 的 div 搜索类 'message' + response[i][1](包含来自 MySQL 的唯一 ID)?

我尝试使用“.hasClass()”,但它不起作用。

【问题讨论】:

  • 你在多个元素上执行hasClass,你确定这是你想要的吗?
  • 不知道有没有必要,我只是想检查一下消息是否已经在屏幕上。它是 JSON 格式的,所以我认为这是可能的。我会试试 if($(".message" + i).length) {append}。

标签: javascript php jquery html


【解决方案1】:

如果您想知道 DIV 中是否有任何元素具有给定的类,您可以这样做:

if ($("#chatScreen").find(".message"+response[i][1]).length > 0) {

你可以重构它,这样你就不必每次循环都搜索#chatScreen

var chatScreen = $("#chatScreen");
for(var i = 0; i < response.length; i ++) {
    if(chatScreen.find(".message"+response[i][1]).length > 0) {
        chatScreen.append($("<div>",{
            class : 'message' + response[i][1],
            html  : response[i][0] + ' ' + response[i][4]
        }));
    }
}

【讨论】:

  • @LcSalazar 我差点就这么写了,我决定用明确的find 让它更清楚。
  • 如果您愿意,您也可以完全省略 &gt; 0 比较,因为数字 0 是一个虚假值 - 我有时会让比较更明确。
  • 你可以,但我不喜欢这样回答问题,因为它使意图不太清楚。
猜你喜欢
  • 1970-01-01
  • 2021-09-06
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多