0

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 exist ,it should trigger onerrorevent and run function onc() to add some CSS and load another picture, but it didnt run function onc() and when I access console ,it shows Uncaught SyntaxError: Unexpected token ILLEGAL .

<button id='a' onclick="onc();">aaa</button>
<div></div>

function onc(){
	var path1= 'images/1h.jpg';//Does not exist
	var path2= 'images/1s.jpg';//exist
	var tmp = "<img src='"+path1+"' onerror='nofind(this,"+path2+");' /> ";
	$('div').html(tmp);
}
I searched some answers, it seems caused by "" or '', but I really don't know how to fix my code. Thanks.

0

1 Answer 1

7

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:

function onc(){
    var path1= 'images/1h.jpg';//Does not exist
    var path2= 'images/1s.jpg';//exist
    var 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.])

Sign up to request clarification or add additional context in comments.

2 Comments

really thanks T.J! it works. it puzzled me so long time. You are so cool!
@leo: :-) No worries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.