简体   繁体   中英

jQuery.html() - The JavaScript code is executed but disappears

I am developing a small editor to add widgets (HTML, CSS and Javascript) to a site.

  • The user types into a field the widget code.
  • When validating, the code of the widget is added to the page.
  • The user can edit the code (which is retrieved from the DOM).

Except that I have a problem to retrieve the javascript code. Indeed, it is well executed, but disappears from the DOM. There is something that escapes me!

I simplified my problem here: HTML code:

<textarea id="code">
    &lt;script type=&quot;text/javascript&quot;&gt;alert(&quot;code&quot;);&lt;/script&gt;
</textarea>
<div id="target"></div>

Javascript code:

$("#target").html($("#code").val());
alert($("#target").html());

Try it out : http://jsfiddle.net/8uhB8/3/

This example insert javascript code (a simple javascript alert) and tries to retrieve it.

Do you have any idea?

Thanks!

$("#target").html($("#code").html());
alert($("#target").html());

Fiddle.

Because you are using HTML characters you need to use .html() in this case.

That's how .html() works. It assigns .innerHTML with all the structural parts of the HTML. But assigning innerHTML doesn't execute scripts. So jQuery pulls all the scripts out of the HTML, and puts them in a <script> node to execute them. This node is only temporary, and is removed by the time .html() completes. But the scripts are still executed.

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