jquery - Javascript eval() not always working on text appended to contents of a div -


i use ajax load dynamic content #main_content element:

var con = document.getelementbyid('main-content'); con.innerhtml = xhr.responsetext; 

however, innerhtml not run js in script elements. evaluate them, use

$("#main-content").find("script").each(function(i) {   eval($(this).text());   console.log($(this).text); }); 

one of loaded pages has following <script> element gets executed, , works expected:

<!-- ajax response --> <script>alert(123);</script> 

however, if define functions in ajax request, come undefined when attempt call them:

<!-- ajax response --> <script> function func() {   alert(123); } </script> 

i not sure why first <script> element gets evaluated , executed, , second 1 not. both being called same function load , evaluate contents of div.

the problem that, in non-strict mode, global variables evaluated direct eval call become local variables of scope called eval:

var code = "var foo = 123"; (function() {   eval(code); // direct call   foo; // 123 })(); foo; // referenceerror: foo not defined 

in strict mode there restricctions, variable in not created in local scope neither.

instead, if want variables become global, can use indirect eval call:

var code = "var foo = 123"; (function() {   window.eval(code); // indirect call   foo; // 123 })(); foo; // 123 

this explained in 10.4.2 - entering eval code.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -