Skip to content Skip to sidebar Skip to footer

Javascript Uncaught Syntaxerror: Unexpected Token Illegal

I tried to run below code but chrome showed Unexpected token ILLEGAL . Can anyone help ? When I click the button, it should add the tag, and when it find images/1h.jpg it does not

Solution 1:

In the rendered JavaScript in the HTML attribute text, the string you have in path2 won't be in quotes, it'll look like this:

onerror='nofind(this,images/1s.jpg);'

One solution is to put it in quotes:

var tmp ="<img src='"+path1+"' onerror='nofind(this,\""+path2+"\");' /> ";
// Change is here -----------------------------------^^---------^^

...which renders like this:

onerror='nofind(this,"images/1s.jpg");'

A better solution, though, would be not to use an onXyz attribute at all. There's no reason to. Instead, use modern event handling:

functiononc(){
    var path1= 'images/1h.jpg';//Does not existvar path2= 'images/1s.jpg';//existvar img = $("img").on("error", function() {
                  nofind(this, path2);
              }).attr("src", path1);
    $('div').html(img);
}

Note that we hook the error event before setting the src attribute. This may not be strictly necessary with error depending on the reason for the error, but it's a good habit to get into and it can matter quite a lot for the related load event. (It's a common misconception that you can hook the load event after setting src; it works most of the time, but may not if the browser has the image cached and the cache settings for it allow the browser to reuse it without revalidating it, in which case the browser may fire the load event as soon as src is set and, not seeing any JavaScript handlers, doesn't queue them to run when the JavaScript thread is next free to run handlers. [There is only one main JavaScript UI thread, but browsers are multi-threaded.])

Post a Comment for "Javascript Uncaught Syntaxerror: Unexpected Token Illegal"