为什么jquery的.load()忽略< script>? [英] why does jquery's .load() ignore <script>?

查看:85
本文介绍了为什么jquery的.load()忽略< script>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个每个常见页面a.html如下所示:

I have a every common page a.html which looks like this:

<html>
  <head>
    <script type="text/javascript" src="xyz.js" > </script>
  </head>
  <body>
    <div> ... </div>
  </body>
</html>

在b.html中,我使用jquery的 .load()函数到 div

In b.html, I use jquery's .load() function to a div.

$("#myDiv").load("a.html")  

它有效。 xyz.js的内容与a.html一起加载。但为什么没有< script> 标签?我打开萤火虫看源头。有一个但没有一个< script>

It works. The xyz.js's content is loaded along with a.html. But why isn't there a <script> tag? I open firebug to see the source. There is a's but no a's <script>.

我想要<脚本> 因为我需要它来查找相对路径。
这个问题

I want the <script> because I need it to find relative path. (this question)

编辑:我尝试使用 .get() .html()。没有帮助。

I tried to use .get() and .html(). Didn't help.

Edit2:标题不太合适。 xyz.js运行。但没有< script>

The title is not very appropriate. The xyz.js runs. But no <script>.

推荐答案

.load()函数有目的地从加载的内容中删除< script> 标记。当您为其提供要加载的纯URL时,它将在加载内容并将其添加到DOM后执行脚本。但是,如果您使用在第一个参数中之后添加选择器的技巧:

The .load() function purposefully strips out <script> tags from the loaded content. When you give it a plain URL to load, it will execute the scripts after loading the content and adding it to the DOM. However, if you use the trick of adding a selector after the URL in the first argument:

$('#foo').load("http://some.domain.com/blah #special-div");

然后它剥离< script> 标签,但执行它们。

then it strips the <script> tags but it does not execute them.

为什么?我不知道。

现在,请注意从< html> 标签加载整个页面如果一个浏览器会完成它,那么进入另一个页面的元素会导致某种类型的Frankenstein怪物出现在DOM中。通常,当您使用.load()来抓取内容片段来更新页面时,您的服务器应该响应一个页面,而不是整个页面。 jQuery处理允许在实际URL之后使用选择器的目的是让你删除一个页面的块,这真的很酷,但它有一个缺点,即在这种情况下不会执行脚本。

Now, please note that loading an entire page from the <html> tag on down into an element of another page is going to result in some sort of Frankenstein monster of a DOM, if a browser will do it at all. Generally, when you use ".load()" to grab fragments of content to update a page, your server should respond with a piece of a page, not the whole thing. The jQuery deal with allowing a selector after the actual URL is intended to let you strip out a chunk of a page, which is really cool, but it has that drawback that the scripts won't be executed in that case.

这篇关于为什么jquery的.load()忽略&lt; script&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆