[英]Javascript : how inject a variable with html content to a data-attribute appended?
我希望在DATA属性中插入一个包含HTML代码的变量(a href ... data-content = ...),由于插入的代码删除了一些字符,突然间它无法正常显示,因此效果不佳。
这是使用的代码
function uploadProgress(file)
{
var ext = file.split('.').pop();
var fileUrl = '/playerFiles/'+file;
if(ext == 'mp4')
{
var preview = '<video autoplay loop muted width="250"><source src="'+fileUrl+'" type="video/mp4">Your browser does not support the video tag.</video>';
}
else
{
var preview = '<img src="'+fileUrl+'" width="250">';
}
var showtime = $('#'+id).find('td.showtime');
showtime.html('<a href="#" class="preview" data-toggle="popover" data-html="true" data-content="'+preview+'"><i class="fa fa-file-o"></i> Aperçu</a>');
}
和我的HTML输出返回此:
<a href="#" class="preview" data-toggle="popover" data-html="true" data-content="<img src=" playerfiles="" img_0006.jpg"="" width="250" data-original-title="" title="" aria-describedby="popover45746">"><i class="fa fa-file-o"></i> Aperçu</a>
为什么不起作用? 我该怎么办?
谢谢
好吧,让我们首先解决此问题:在预览变量中有双引号,应使用'\\'将其转义,例如:
var preview = '<img src=\"' + url + '\" width=\"250\">';
或者最好在var中使用单引号
var preview = "<img src='" + url + "' width='250'>";
但我认为在此attr中存储html并不是一种好方法-最好在此处仅将url和html存储在单独的模板中。 或在页面加载时呈现隐藏的元素
代码的问题是预览值中包含特殊字符。 如果使用下面给出的代码,则可以解决问题,这不是正确的方法,请避免使用这种编码样式。将数据属性用于整数,小字符串值等。诸如html或长字符串值等内容都可以使用public属性或隐藏的控件。
function uploadProgress(file)
{
var ext = file.split('.').pop();
var fileUrl = '/playerFiles/'+file;
if(ext == 'mp4')
{
var preview = '<video autoplay loop muted width="250"><source src="'+fileUrl+'" type="video/mp4">Your browser does not support the video tag.</video>';
}
else
{
var preview = '<img src="'+fileUrl+'" width="250">';
}
var showtime = $('#'+id).find('td.showtime');
showtime.html('<a href="#" class="preview" data-toggle="popover" data-html="true" ><i class="fa fa-file-o"></i> Aperçu</a>');
$(".preview").data("content",preview);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.