构造onclick='location.href='将JS变量转换为HTML
Proper syntax to construct onclick='location.href=' with JS variable into HTML
我正在循环使用包含URL的变量sortedlist[i].description
的一些数据。我需要构建以下HTML输出:
<div onclick="location.href='http://XXXXXX' class="MusicItem">
我正在用一个名为output
的变量构建我的HTML输出,该变量累积到我的页面的整个主体中。
output += '<div onclick="location.href="' +
sortedlist[i].description + '" class="MusicItem">';
以上当然失效了。显然,我的引用用法/语法有问题,但我已经尝试了各种方法:
- 单引号和双引号交替使用。
- 只使用单引号。和
- 使用双亲代替单引号等
您可以像这样转义引号:
output += '<div onclick="location.href=''' + sortedlist[i].description + '''" class='"MusicItem'"></div>';
生成以下字符串:
<div onclick="location.href='https://google.com'" class="MusicItem"></div><div onclick="location.href='http://stackoverflow.com'" class="MusicItem"></div>
试试这个
output += '<div class="MusicItem" data-url="'+sortedlist[i].description+'"></div>'
并附加一个点击事件,如下所示
var item = document.querySelectorAll(".MusicItem");
for(var i = 0; i < item.length; i++){
item[i].addEventListener("click", function(event){
window.location.href = this.dataset.url;
});
}
或者如果你只是想在点击事件时重定向到新页面,那么最好使用锚标记
可能的解决方案是
output += sortedlist.map(function(item){
return '<a href="'+item.description+'" class="MusicItem">'
});
相关文章:
- 将标量变量转换为javascript中包含变量的数组
- 使用Javascript将多行变量转换为单行变量
- 变量转换为另一个“未定义”的变量
- 如何在javascript中将String变量转换为int
- 提交时将JavaScript变量转换为PHP表单
- 在d3.js中将局部变量转换为全局变量
- 在php函数中将php变量转换为javascript变量
- AngularJS变量转换为html<对象>属性
- 正在将字符串变量转换为数组
- 将变量转换为 json 路径
- 将 MVC 4 Razor 变量转换为 JavaScript 数组
- 如何在 JavaScript 中将局部变量转换为全局变量
- 如何将 jstl/JSP 变量转换为 JavaScript 变量
- 如何将变量转换为对象
- 如何使用 Javascript 将变量转换为字符串
- 在将会话变量转换为 javascript 变量时丢失特殊字符
- 如何在函数内将未定义的变量转换为对象
- 在按键和鼠标单击后将函数变量转换为全局变量
- 如何在javascript中将整数变量转换为字符串
- Javascript变量转换为Applescript