有没有办法从 html 内容中提取有效的脚本并使用 jQuery 执行它?
假设我有这样的事情:
<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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于它使用
text()
,因此它应该删除所有 HTML,因此您应该能够根据需要对代码应用任何代码荧光笔。例如,如果您使用 StackOverflow 代码荧光笔并想要选择代码,则 text() 将返回您所期望的内容:
而
html()
可能会返回Which 显然无法评估。
如果您不打算进行任何代码突出显示,那么这不是问题。
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:
Whereas
html()
would probably returnWhich obviously can't be evaluated.
If you don't plan on doing any code highlighting then it's a non-issue.
您可以对其调用
eval()
,尽管我会重新评估您的方法,如下所示:您可以在此处进行测试。这只是说明它可以做到,但如果可能的话,您应该尽量避免这种情况,它至少存在安全和性能问题。
You can call
eval()
on it, though I would re-evaluate your approach, like this: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.