简体   繁体   中英

Insert script tag in textarea with jQuery

I'm trying to create a textarea with an embed code, so a user can copy that code. I have two methods of embedding (first method is script with paired div), the other one is iframe). I enable the user to select a size of the embedded widget through parameters sent to the server.

The textarea content should be this <script src="http://mysite.com/embed/product_id/width/height"></script>

Usually, that would be set as an encoded HTML (& lt; & gt;) when printed out through the HTML, but in this case I need to set it through Javascript.

So this doesn't work:

$('textarea.embed_code').val('<script src="http://mysite.com/embed/product_id/width/height"></script>');

The closing tag breaks the initial script tag where this line is set.

Any suggestion about how to change the width and height in the script source would be fine too (regex, string replace ...), in which case I'll just print out the textarea content from the HTML.

Any other tag works fine, the issue is just with <script>

To include the string "</script>" as data in a <script> element, escape the / : "<\\/script>" . This will break the HTML end tag syntax while being equivalent in JavaScript string literal syntax.

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