Say I have a something like this:
<p id="script">$("p").css("color", "red");</p>
Is there a way to select th开发者_如何学Ce script contained within the tag and execute it using jQuery? In this case, the script
$("p").css("color", "red");
would be executed and then cause itself to be rendered with a red font color within the paragraph tag. I can select the text perfectly fine, but haven't found a way to actually execute it. I don't want other solutions - I am aware of them, I am just trying to figure out if this specific case is possible, and if so, how. Thanks.
eval($("#script").text())
Since it uses text()
, it should strip out any HTML so you should be able to apply any code highlighters to the code if you wanted to.
For example, if you were using the StackOverflow code highlighter and wanted to select the code, text() would return what you expect:
eval($("#script").text())
Whereas html()
would probably return
<span class="kwd">eval</span><span class="pun">(</span><span class="pln">$</span><span class="pun">(</span><span class="str">"p #script"</span><span class="pun">).</span><span class="pln">text</span><span class="pun">())</span><span class="pln"><br></span>
Which obviously can't be evaluated.
If you don't plan on doing any code highlighting then it's a non-issue.
You can call eval()
on it, though I would re-evaluate your approach, like this:
eval($("#script").html());
You can test it out here. This is just illustrating it can be done, but you should try and avoid this if at all possible, it has security and performance issues at the very least.
精彩评论