简体   繁体   中英

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. I need to build the following HTML output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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