首页 > 解决方案 > 为什么我的数据模板不使用 javascript 渲染新图像?

问题描述

每次发送新消息时,都会自动为每个用户显示。消息由消息、时间戳和发件人的个人资料图片组成。使用 HTML 模板,将显示消息和时间戳,但不显示图像。

HTML


<!--template for javascript incoming-->
                  <template id="incoming_template">
                    <div class="incoming_msg_img" data-template="temp_img">

                    </div> 
                      <div class="received_msg">
                        <div class="received_withd_msg" aria-describedby="name">
                          <small id="name" data-template="sender">User</small>
                          <p data-template="temp_message"></p>
                          <span class="time_date" data-template="temp_time"></span></div>
                      </div>
                  </template>

JavaScript

$(function () {

                // Get template
                var template = $("#incoming_template").html();

                var template_dom = $('<div/>').append(template);            
                
                // Create a new row from the template
                var $row = $(template);
                

                var img = "<img src=../static/avatars/beard.png>";


                // Add data to the row
                $row.find("p[data-template='temp_message']").text(data.msg);
                $row.find("span[data-template='temp_time']").text(data.timestamp);
                $row.find("small[data-template='sender']").text(data.sender);
                $row.find("div[data-template='temp_img']").html(img);
            
                // Add the row to the table
                $("#newmsg").append($row);

                updateScroll();
            });

标签: javascripthtmljquery

解决方案


目前,您正在将一些 HTML 字符串包装在 jQuery 对象中。您需要从模板 HTML 中临时创建一个 DOM 对象,以便 jqueryfind函数可以正确地找到 DOM 树中的元素。请参阅以下修订:

// Get template
var template = $("#incoming_template").html();

// Add this line to your code
var template_dom = $('<div/>').append(template);

// Create a new row from the template
var $row = $(template_dom);

然后更改此行:

$row.find("div[data-template='temp_img']").text(img);

对此:

$row.find("div[data-template='temp_img']").html(img);

因为您要附加标记而不是一些文本。

在此处阅读更多内容:jQuery: text() 和 html() 有什么区别?


推荐阅读