有没有办法从 html 内容中提取有效的脚本并使用 jQuery 执行它?

发布于 2024-09-25 04:32:02 字数 317 浏览 0 评论 0原文

假设我有这样的事情:

<p id="script">$("p").css("color", "red");</p>

有没有办法选择标签中包含的脚本并使用 jQuery 执行它?在这种情况下,脚本

$("p").css("color", "red");

将被执行,然后导致其自身在段落标记内以红色字体颜色呈现。我可以完美地选择文本,但还没有找到实际执行它的方法。我不需要其他解决方案 - 我知道它们,我只是想弄清楚这个特定情况是否可能,如果可以,如何实现。谢谢。

Say I have a something like this:

<p id="script">$("p").css("color", "red");</p>

Is there a way to select the 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

行雁书 2024-10-02 04:32:02
eval($("#script").text())

由于它使用 text(),因此它应该删除所有 HTML,因此您应该能够根据需要对代码应用任何代码荧光笔。

例如,如果您使用 StackOverflow 代码荧光笔并想要选择代码,则 text() 将返回您所期望的内容:

eval($("#script").text())

html() 可能会返回

<span class="kwd">eval</span><span class="pun">(</span><span class="pln">
lt;/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 显然无法评估。

如果您不打算进行任何代码突出显示,那么这不是问题。

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">
lt;/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.

百思不得你姐 2024-10-02 04:32:02

您可以对其调用 eval() ,尽管我会重新评估您的方法,如下所示:

eval($("#script").html());

您可以在此处进行测试。这只是说明它可以做到,但如果可能的话,您应该尽量避免这种情况,它至少存在安全和性能问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文