javascript - 为什么我的数据模板不使用 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();
});
解决方案
目前,您正在将一些 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() 有什么区别?
推荐阅读
- jira - 如何获得 Katalon 执行结果?
- angular - 页面加载时间统计
- typescript - 当组件具有自定义构造函数时,Vue 存储未定义
- python-3.x - 离散变量的熵估计
- c# - 如何修复错误参数 3:无法在 c# 中从 'System.DateTime' 转换为 'Microsoft.Win32.Registry ValueOptions'
- python - 在 Keras 中实现自定义损失函数时遇到问题
- javascript - 如何在角度 6 的单个图像中使用多个裁剪
- r - 围绕值的日期的 groupby 问题:二进制运算符的非数字参数
- angular - 是否不可能在订阅中捕获错误?
- linux - 当接收到带有空格和双引号的字符串时,如何正确解析在 Linux 上运行的 Jenkins 中的构建参数?