Jquery correct selection of script tag content

I have a one-page web application using jquery and a set of built-in templates. A template may contain a tag as shown below:

<script type="html/template" id="sample">

<script type="text/javascript" charset="utf-8">alert('x');</script>


</script>

and jquery code to extract the template

$("#sample").html();

Jquery command output above

<script type="text/javascript" charset="utf-8">alert('x');

Instead

<script type="text/javascript" charset="utf-8">alert('x');</script>

How can I fix this conclusion?

+5
source share
6 answers

It is expected that there <script>will be a script inside , not HTML.

The browser sees:

<script type="html/template" id="sample">

and begins to interpret everything that subsequently appears as a script when it reaches the inside <script, which is considered just plain text.

The exception is </script>that the browser is looking to switch contexts from script to HTML, so when it sees 1st </script>in:

<script type="text/javascript" charset="utf-8">alert('x');</script>

, script HTML, script node :

<script type="text/javascript" charset="utf-8">alert('x');

, , , .

+1

, .

 var a = $("#sample").html() +'</'+'script>';

 alert(a);​

: http://jsfiddle.net/Sg5W8/

+2

script HTML, script validator, Stray end tag script.

script - - .

+1

, html/template mime-type , . script -tag.

0

var c = $("#sample script").html();
var type = $("#sample script").attr("type");
var chset =  $("#sample script").attr("utf-8");

var ouptut = '<script type="'+ type +'" charset="'+ charset +'">' + c + '</script>'
0

I would suggest, if possible, moving the script. I tried 2 options. The first is with html encode, and the second is a custom script element.

1. html encode

http://jsfiddle.net/Ae48z/

   <script type="html/template" id="sample">

    &lt;script type=&quot;text/javascript&quot; charset=&quot;utf-8&quot;&gt;alert(&#39;x&#39;); &lt;/script&gt;

Js

  var out = $("#sample").html(this);
  console.log(out);

2.script replace

http://jsfiddle.net/2G7gj/

 <script type="html/template" id="sample">
     <xscript type="text/javascript" charset="utf-8">alert('x');</xscript>

 </script>

var out = $('#sample').html().replace(/xscript/g,'script');
console.log(out )

0
source

All Articles