2

I'm creating anchor tag dynamically like

for (var i = 0; i < json.length; i++)
{
      <td><a href='#'  id=" + json[i].id + " onclick=getId('" + json[i].id + "','"+ json[i].text +"')>" + json[i].text + " </a></td>
}

and In the onclick function I have defined like

function getId(ID,text)
{
      console.log(ID);
      console.log(text);
}

In this onclick event If the text value doesn't contain any space or gap between word to word, I'm able to get the text value in console, In-case If text contains any spaces then It is showing error like Unexpected token ILLEGAL.

putvande
  • 15,068
  • 3
  • 34
  • 50
charan
  • 292
  • 8
  • 24
  • Can you post how some of the finished/generated anchor tags look like? You might have something inside which is breaking your syntax – thmshd Aug 07 '13 at 08:05
  • It is possible that your text value could have a trailing invisible character or instead of spaces, they are these characters. It would help to know the source of the JSON and also if there are any string checking done there. See this http://stackoverflow.com/questions/12719859/syntaxerror-unexpected-token-illegal – Calvin Aug 07 '13 at 08:18

2 Answers2

1

<a href='#' id=" + json[i].id + " onclick=getId('" + json[i].id + "','"+ json[i].text +"')>" + json[i].text + " </a>

Above code might work, but IMHO its not good practice.

Try this, I prefere it this way and much cleaner.

var a = document.createElement('a');
a.setAttribute('id',json[i].id);
a.setAttribute('href',"#");
a.innerHTML = json[i].text;
a.onclick = function(e) {
    getId(json[i].id, json[i].text);
    e = e || window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) {
        e.stopPropagation();
    }
    return false;
};
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

It is possible that your text value could have an invisible character that causes the Unexpected token ILLEGAL.

No visible cause for "Unexpected token ILLEGAL" should explain more on ILLEGAL characters.

Remove zero-width space characters from a JavaScript string could help you try to remove these characters.

Community
  • 1
  • 1
Calvin
  • 1,305
  • 8
  • 17