构造onclick='location.href='将JS变量转换为HTML

Proper syntax to construct onclick='location.href=' with JS variable into HTML

本文关键字:变量 转换 HTML JS location onclick 构造 href      更新时间:2023-09-26

我正在循环使用包含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">';

以上当然失效了。显然,我的引用用法/语法有问题,但我已经尝试了各种方法:

  1. 单引号和双引号交替使用。
  2. 只使用单引号。和
  3. 使用双亲代替单引号等

您可以像这样转义引号:

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">' 
});