简体   繁体   English

如何使用 Javascript 检查页面中的元素是否已存在?

[英]How to check if elements in a page already exist using Javascript?

I am building a chat app using flask socketio.我正在使用 flask socketio 构建一个聊天应用程序。 So I am trying to implement chat history, but the problem I run into is that whenever a new user connects, the app sends the new user the chat history, as well as to the old user, thus resulting in duplicated chat history for the old user.所以我正在尝试实现聊天历史记录,但我遇到的问题是,每当新用户连接时,应用程序都会将聊天历史记录发送给新用户以及旧用户,从而导致旧用户重复聊天记录用户。 I've tried everything server side, but I think the only way is through Javascript client side.我已经尝试了所有服务器端,但我认为唯一的方法是通过 Javascript 客户端。 Is there any way that when Javascript gets the chat history, could I make JS first check if that messages don't already exist on the page, and then append them?有没有什么办法可以让 Javascript 获取聊天记录时,我可以让 JS 先检查页面上是否不存在该消息,然后再检查 append 吗?

Here is a screenshot on what is happening.这是正在发生的事情的屏幕截图。 visual representation of what's happening正在发生的事情的视觉表示

Code(Client-side Javascript)代码(客户端Javascript)

  const socket = io.connect("http://127.0.0.1:5000");

socket.on('connect', function() {

  socket.emit('sync_messages', {
    dname: "{{dname}}"
  });

});

Code (Server-side Flask Socketio)代码(服务器端Flask Socketio)

@socketio.on('sync_messages')
def handle_sync(data):
        socketio.emit('show_all_messages', messages)

Code (Client-side again)代码(又是客户端)

socket.on('show_all_messages', function(data) {
 // console.log(data);
  len = data.length;
  for (i = 0; i < len; i++) {
    const newNode = document.createElement('div');
    newNode.innerHTML = data[i];
    document.getElementById('messages').appendChild(newNode);
  }

})

Really simple.真的很简单。 You can any give any types of attribute to that element which you need to find and do您可以为需要查找和执行的元素提供任何类型的属性

function checkElement(){
   if(document.querySelector(/*Selector*/)){
      return true;
   }
   else{return false;}
}

then just call this function when you need.然后只需在需要时调用此 function。 document.querySelector in if statement will automatically look for you does html element exist or not if 语句中的 document.querySelector 将自动查找您是否存在 html 元素

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

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