简体   繁体   English

避免在 div 中嵌入媒体以通过 innerHTML 添加刷新

[英]Avoiding media embedded in div to get refreshed on addition by innerHTML

I am building a chat web app using socket.io and node.I am adding user's chat in a div using innerHTML.But the problem is that when a new message is added to the chat container(div block),the previous media present in chat-container reloads every time a new chat is added.I want to avoid this.Can anyone help me to find a solution for this?I would love to hear your ideas.我正在使用 socket.io 和节点构建聊天 web 应用程序。我正在使用 innerHTML 在 div 中添加用户的聊天。但问题是,当将新消息添加到聊天容器(div 块)时,聊天中存在的先前媒体 -每次添加新聊天时容器都会重新加载。我想避免这种情况。谁能帮我找到解决方案?我很想听听你的想法。 Here is the abstract code i am using这是我正在使用的抽象代码

HTML
<input type = "text" id = "message" placeholder="Type something..." /><i onclick = "sendMessage()" style="color:green;" title="Send" id="sendbtn"></i>

i am not using input in form element我没有在表单元素中使用输入

clientJS:客户端JS:

function sendMessage(){
   var msg = document.getElementById("message").value;
   if (msg) {
      postFile({message: msg,id:id, user: user, color: color,roomid:nativeRoom});
      socket.emit("msg", { message: msg,id:id, user: user, color: color,roomid:nativeRoom});             
   }
}
socket.on("newmsg",function(data){
   postFile(data);
   //Actually postFile is here because it can include video,audio as well
});
function postFile(data){
//here i want to prevent message-container div from reloading its previous media(i have ignored most of the css code to make it precise)
   document.getElementById('message-container').innerHTML += '<div class="messages '+data.user+'chatpiece" id="'+data.id+'"><div><div><b>'+data.user+'</b><img src="'+userprofileimagelink+'"/></div><span>' +{time_when_message_posted} +'</span></div><hr><span style="max-width:100%;word-wrap:break-word;font-size:1.1em;" class="messagemain">' +data.message+"</span></div>"; 
}

server-side:服务器端:

socket.on('msg',function(data){
  socket.broadcast.to(data.roomid).emit('newmsg',data);
});

I want to avoid reload of video and audio media present in chat container when a new message will be added.我想避免在添加新消息时重新加载聊天容器中存在的视频和音频媒体。 How may i achieve this?我怎样才能做到这一点?

Consider appendChild instead of modifying the .innerHTML each time.考虑appendChild而不是每次都修改.innerHTML Once a web page renders html, it becomes DOM.一旦 web 页面呈现 html,它就变成了 DOM。 Append to the DOM instead of "converting DOM back into html via innerHTML each time and then appending additional HTML strings to that conversion" (like you're doing). Append 到 DOM,而不是“每次通过innerHTML将 DOM 转换回 html,然后将额外的 HTML 字符串附加到该转换”(就像你在做的那样)。 Learn about DOM if you don't know it.如果您不了解DOM ,请了解它。

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

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