I have a chat system and I'm showing the messages using 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:
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. 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)?
I tried to use ".hasClass()" but it doesn't work.
If you want to know if there's any element in the DIV with a given class, you can do:
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:
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]
}));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.