简体   繁体   中英

div inside script tag throws exception - why

I'm trying to insert a template into DOM using jQuery but it gives me the error - Uncaught SyntaxError: Unexpected token < . Why so?

Works fine:

$('body').children().last().after('<div></div>');

Throws exception:

$('body').children().last().after('<script><div></div></script>');

Because <div></div> is not valid JavaScript. jQuery is trying to generate a <script> element with the innerHTML of <div></div> .

Note that your approach is probably wrong. Please see What is the XY Problem?

If you want to use text/template templates, you have to include that in the <script> element's attributes:

$('body').children().last().after('<script ><div></div></script>');

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