Function javascript in html string

Asked

Viewed 220 times

0

I have a loop that displays multiple Ivs,and I have a span that has a function called remove, however when click to run the error function always but in html it is correct.

(function() {
        //Seta valores padrões
        document.querySelector('[data-js="pageTitle"]').innerHTML = datasource[0].pageName;
        document.querySelector('[data-js="title"]').innerHTML = datasource[0].title;
        document.querySelector('[data-js="subtitle"]').innerHTML = datasource[0].subtitle;
        document.querySelector('[data-js="logo"]').src = "./images/"+datasource[0].logo;

        localStorage.defaultData = JSON.stringify(datasource[0].data)

        if(localStorage.default === 'true'){
          var info = _getObject({key:'defaultData', typeResponse:'object'});
        }else{
          var info = _getObject({key:'links', typeResponse:'object'});
        }

        var el = document.querySelector('[data-js=items]');
        var elDef  = "<a href='#openModal' class='blocks blocks__default'>+</a>";
        var cnt = "";
        for (var i = 0; i < info.length; i++) {
        cnt += "<span class='remove' onclick='remover("+info[i].id+")'>x</span>";
        cnt += "<a href="+info[i].link+" id="+info[i].id+" target='_blank'>";
        cnt += "<div class='blocks' title="+info[i].description+">";
        cnt += "<h5>"+info[i].title+"</h5>";
        cnt += "<img src='./images/"+ info[i].logo +"' alt='RH web'>";
        cnt += "</div>";
        cnt += "</a>";
        }
        cnt += elDef;
        el.innerHTML = cnt;
      })();

function remover(id){
        console.log(id);
      }

In html it appears straight

<span class="remove" onclick="remover(301ec16263120ee1a113a5)">x</span>

But when click to run always returns error. Uncaught SyntaxError: Invalid or unexpected token

  • You can give an example of one of those info[i].id? is a number or a word?

  • Friend where you create the datasource variable' ?

  • info[i].id a string made up of letters and numbers. datasource is a file called externally that has an object. @fsola was just that.

1 answer

1


Pass the quoted parameter to the function.

Substitute:

cnt += "<span class='remove' onclick='remover("+info[i].id+")'>x</span>";

For:

cnt += "<span class='remove' onclick='remover(\""+info[i].id+"\")'>x</span>";

The final result should be:

<span class="remove" onclick='remover("301ec16263120ee1a113a5")'>x</span>
  • that’s right, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.