Reputation: 47945
Tried this :
<a href="#" id="showAlert">Click me</a>
<div id="pasteContent"></div>
var elemFunc = '<script>alert("myString");</script>';
$("#showAlert").click(function () {
$("#pasteContent").html(elemFunc);
});
What I'd like to do is to append the string alert(myString); (which is a script) that must be executed... how can I do? Is it not correct?
Upvotes: 1
Views: 176
Reputation: 18022
Since what you're going equates to an eval
, and eval IS evil, You can use an external script and $.getScript()
, to load it via ajax...
$.getScript("http://scriptURL.com/script.js", function(){ init(); });
Upvotes: 0
Reputation: 10946
Try this:
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescript";
$("head").append(s);
Note that the script will load and you can access the variables inside it, but you wouldn't see the actual tag in the DOM.
Upvotes: 0
Reputation: 3799
Try this:
var elemFunc = '<script>alert("myString");</' + 'script>';
If you have your JS inside your HTML
Upvotes: 0
Reputation: 7887
try it whit a jquery script object like this
var elemFunc = $('<script>')
.attr('type', 'text/javascript')
.html('alert("myString");');
$("#showAlert").click(function () {
$("#pasteContent").append(elemFunc);
});
Upvotes: 0
Reputation: 348972
Add a backslash before /
in </script>
: http://jsfiddle.net/kxALH/3/
Your code failed, because </script>
is considered as a close tag for your fiddle script. As a result, your first fiddle looked somewhat weird.
Note: If you want to execute an arbitrary string of code, $.globalEval('alert("myString")');
may suit better.
Upvotes: 5