简体   繁体   English

为什么jquery的.load()会忽略<script>?

[英]why does jquery's .load() ignore <script>?

I have a every common page a.html which looks like this: 我有一个每个常见的页面a.html,看起来像这样:

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

In b.html, I use jquery's .load() function to a div . 在b.html中,我将jquery的.load()函数用于div

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

It works. 有用。 The xyz.js's content is loaded along with a.html. xyz.js的内容与a.html一起加载。 But why isn't there a <script> tag? 但为什么没有<script>标签? I open firebug to see the source. 我打开萤火虫看源头。 There is a's but no a's <script> . 有一个但没有一个<script>

I want the <script> because I need it to find relative path. 我想要<script>因为我需要它来查找相对路径。 ( this question ) 这个问题

Edit: I tried to use .get() and .html() . 编辑:我尝试使用.get().html() Didn't help. 没有帮助。

Edit2: The title is not very appropriate. Edit2:标题不太合适。 The xyz.js runs. xyz.js运行。 But no <script> . 但没有<script>

The .load() function purposefully strips out <script> tags from the loaded content. .load()函数有目的地从加载的内容中删除<script>标记。 When you give it a plain URL to load, it will execute the scripts after loading the content and adding it to the DOM. 当您为其提供要加载的纯URL时,它将在加载内容并将其添加到DOM后执行脚本。 However, if you use the trick of adding a selector after the URL in the first argument: 但是,如果您使用在第一个参数中的URL 之后添加选择器的技巧:

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

then it strips the <script> tags but it does not execute them. 然后剥去<script>标签,但它执行它们。

Why? 为什么? I don't know. 我不知道。

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. 现在,请注意,从<html>标签向下加载整个页面到另一个页面的元素将导致DOM的某种Frankenstein怪物,如果浏览器将完全执行它。 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. 通常,当您使用“.load()”来抓取内容片段来更新页面时,您的服务器应该响应一个页面,而不是整个页面。 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处理在实际URL之后允许选择器的目的是让你去掉一个页面的块,这真的很酷,但它有一个缺点,就是在这种情况下脚本不会被执行。

Because, it cannot run the script inside the <SCRIPT> tag. 因为,它无法在<SCRIPT>标记内运行脚本。 jQuery has .getScript() to call for scripts only. jQuery只有.getScript()来调用脚本。 Check here 点击这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM