使用 script 标签将 HTML 注入 DOM
我们允许用户在他们的页面上放置一个
<script language="javascript" src="oursite/script.php"></script>
标签,然后该标签应该将我们网站的一些内容嵌入到他们的网站中。目前 script.php 包含 document.write("从数据库加载的一些内容"),但是有一些限制。
无论如何,我可以使用 jQuery 实现同样的事情吗?我如何告诉 jQuery 将一段 HTML 代码准确地放在 script 标签所在的位置? document.write() 可以做到这一点,但我不知道如何使用 jquery 做到这一点。 (我们已经通过 script.php 向客户端提供了 jquery js 代码。
We allow users to place a
<script language="javascript" src="oursite/script.php"></script>
tag on their page which should then embed some content from our site into their site. Currently script.php contains document.write("some content loaded from the database"), however there are some limitations.
Is there anyway I can have the same thing achieved using jQuery ? How do i tell jQuery to put a certain piece of HTML code EXACTLY where the script tag is ? document.write() can do this, but i'm not sure how to do this using jquery. (we are already providing the jquery js code to the client through script.php.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要 jQuery 来执行
document.write()
。只要它是内联执行的(即不在事件处理程序中,例如$(document).ready()
),它就可以工作。只需确保转义结束脚本标记(如下所示:<\/script>
),以便 HTML 解析器不会将其误认为是实际的结束脚本标记:或者,您可以添加使用 DOM 操作的脚本。如果您想在页面加载后添加脚本,这是您唯一的选择。要将其放置在调用它的脚本标记之后,请为您的脚本标记提供一个 id 并使用
$("#myScript").after("
You don't need jQuery to do a
document.write()
. As long as it is executed inline (ie, not in an event handler such as$(document).ready()
), it will work. Just make sure you escape the end script tag (like this:<\/script>
), so that the HTML parser doesn't mistake it for an actual end script tag:Alternatively, you could add the script using DOM manipulations. If you want to add the script after the page has loaded, this is your only option. To position it after the script tag that is calling it, give your script tag an id and use
$("#myScript").after("<script>")
:您不一定需要使用 jQuery,但您可以。
这里的基本问题是在页面加载时找到脚本节点。
您可以给它一个
id
并希望其他用户的页面上没有重复的 id。但是,如果您知道脚本将在页面加载时进行评估,您也可以这样做:
您当然也可以使用 jQuery 和
var $script = $('script:last');
,但如果您不需要它做其他任何事情,您可以通过不使用它来节省一些加载时间。You don't necessarily need to use jQuery, but you can.
The basic problem here is finding the script node as the page is loading.
You can give it an
id
and hope there are no duplicate ids on the other user's page.But if you know the script will be evaluated as the page is loading, you can also do this:
You can of course use jQuery as well with
var $script = $('script:last');
, but if you don't need it for anything else you can save some loading time by not using it.