【问题标题】:Update text with jquery on socketIO event在 socketIO 事件上使用 jquery 更新文本
【发布时间】:2013-12-06 01:30:52
【问题描述】:

我有以下代码来更新 socketIO 消息的 div 内的文本。该事件被触发了 10 次,所有 console.log 都正常显示,但我的 div 中的文本只更新一次。

socket.on('jobMsg',function(msg){
  if(msg.type==='progress'){
    $('#'+msg.store).parent().text(msg.progress+' %');
    console.log(msg);
  }
});

消息的格式是:

{type: "progress", store: "xxx", progress: 10}

为什么会发生这种情况(最重要的问题)? 还有,我该如何解决这个问题?

此位的玉代码,如果有帮助:

.monitor
  .led(id=res['store'])

【问题讨论】:

    标签: javascript jquery node.js socket.io


    【解决方案1】:

    执行$('#'+msg.store).parent().text('....') 以父元素为目标,并用检索到的文本覆盖所有和任何内容,从而完全删除$('#xxx') 元素,因此下一次没有$('#'+msg.store).parent(),因为它已被删除(不是父元素,但目标元素)。

    改成:

    socket.on('jobMsg',function(msg){
      if(msg.type == 'progress') {
        $('#'+msg.store).text(msg.progress+' %');
      }
    });
    

    【讨论】:

    • 如果我使用它的 id 更改父元素的文本,它是否也会删除子元素?
    • 是的,text() 和 html() 删除所有内容并用传递的字符串替换它。
    • 您可以将文本包装在具有父级内部 ID 的跨度中,然后改为以该跨度为目标。
    猜你喜欢
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多