简体   繁体   English

选择另一个div中的每个div并使用jQuery检查它的类

[英]Select every div inside another div and check it's class with jQuery

I have a chat system and I'm showing the messages using jQuery + JSON + PHP. 我有一个聊天系统,并且正在使用jQuery + JSON + PHP显示消息。 My problem is: I have to select each div inside the div "#chatMessages", that contains the messages, and check it's class to see if it exists, my Ajax code: 我的问题是:我必须在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] contains the name, and the response[i][4] contains the message. response[i][0]包含名称,而response[i][4]包含消息。 It's working fine, but I load this function every 3000ms, so it repeat every message, how can I check div per div searching for the class 'message' + response[i][1] (that contains the unique ID from MySQL)? 它工作正常,但是我每3000毫秒加载一次此函数,因此它会重复每条消息,如何检查每div的div来搜索类'message' + response[i][1] (包含MySQL的唯一ID)?

I tried to use ".hasClass()" but it doesn't work. 我尝试使用“ .hasClass()”,但是它不起作用。

If you want to know if there's any element in the DIV with a given class, you can do: 如果您想知道DIV中是否有给定类的任何元素,则可以执行以下操作:

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

You can refactor it so you don't have to search for #chatScreen every time through the loop: 您可以对其进行重构,这样就不必每次通过循环都搜索#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]
        }));
    }
}

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

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