为了账号安全,请及时绑定邮箱和手机立即绑定

避免在 div 中嵌入媒体,以便在通过内部 HTML 添加时刷新

避免在 div 中嵌入媒体,以便在通过内部 HTML 添加时刷新

明月笑刀无情 2022-09-23 16:59:38
我正在使用 socket.io 和节点构建聊天Web应用程序。我使用innerHTML在div中添加用户的聊天,但问题是,当一条新消息被添加到聊天容器(div块)时,聊天容器中存在的先前媒体会在每次添加新聊天时重新加载。我想避免这种情况。任何人都可以帮我找到解决方案吗?我很想听听你的想法。这是我正在使用的抽象代码HTML<input type = "text" id = "message" placeholder="Type something..." /><i onclick = "sendMessage()" style="color:green;" title="Send" id="sendbtn"></i>我没有在表单元素中使用输入客户: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>"; }服务器端:socket.on('msg',function(data){  socket.broadcast.to(data.roomid).emit('newmsg',data);});我想避免在添加新消息时重新加载聊天容器中存在的视频和音频媒体。我怎样才能做到这一点?
查看完整描述

1 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

请考虑追加孩子,而不是每次都修改 。附加到DOM而不是“通过每次将DOM转换回html,然后将其他HTML字符串附加到该转换中”(就像您所做的那样)。如果您不知道 DOM,请了解它。.innerHTMLinnerHTML



查看完整回答
反对 回复 2022-09-23
  • 1 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信