简体   繁体   English

使用 JS 变量将 onclick='location.href=' 构造为 HTML 的正确语法

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

I'm looping through some data with a var called sortedlist[i].description that contains an URL.我正在使用包含 URL 的名为sortedlist[i].description的 var 遍历一些数据。 I need to build the following HTML output:我需要构建以下 HTML 输出:

<div onclick="location.href='http://XXXXXX' class="MusicItem">

I'm building my HTML output with a var called output which accumulates into the full body of my page.我正在使用一个名为output的 var 构建我的 HTML 输出,该变量累积到我的页面的整个正文中。

output += '<div onclick="location.href="' + 
          sortedlist[i].description + '" class="MusicItem">';

The above of course breaks.以上当然打破了。 I clearly have an issue with my quotation usage/syntax but I've tried it every which way:我的引用用法/语法显然有问题,但我已经尝试过各种方法:

  1. alternating single to double quotes.交替单引号到双引号。
  2. only using single quotes.只使用单引号。 and
  3. using parens in place of the single quotes, etc.使用括号代替单引号等。

Nothing is working.没有任何工作。

You can escape the quotes like this:您可以像这样转义引号:

output += '<div onclick="location.href=\'' + sortedlist[i].description + '\'" class=\"MusicItem\"></div>';

Generating the following string:生成以下字符串:

<div onclick="location.href='https://google.com'" class="MusicItem"></div><div onclick="location.href='http://stackoverflow.com'" class="MusicItem"></div>

Try this尝试这个

output += '<div class="MusicItem" data-url="'+sortedlist[i].description+'"></div>'

and attach a click event like this并附加一个这样的点击事件

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

or if you just want to redirect to new page on click event then better use an anchor tag或者如果您只想在点击事件时重定向到新页面,那么最好使用锚标记

possible solution is可能的解决方案是

output += sortedlist.map(function(item){
    return '<a href="'+item.description+'" class="MusicItem">' 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM