jQuery .load() 调用不会在加载的 HTML 文件中执行 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/889967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:02:36  来源:igfitidea点击:

jQuery .load() call doesn't execute JavaScript in loaded HTML file

jqueryajaxsafari

提问by Mike

This seems to be a problem related to Safari only. I've tried 4 on Mac and 3 on Windows and am still having no luck.

这似乎是仅与 Safari 相关的问题。我已经在 Mac 上尝试了 4 个,在 Windows 上尝试了 3 个,但仍然没有运气。

I'm trying to load an external HTML file and have the JavaScript that is embedded execute.

我正在尝试加载外部 HTML 文件并执行嵌入的 JavaScript。

The code I'm trying to use is this:

我试图使用的代码是这样的:

$("#myBtn").click(function() {
    $("#myDiv").load("trackingCode.html");
});

trackingCode.htmllooks like this (simple now, but will expand once/if I get this working):

trackingCode.html看起来像这样(现在很简单,但会扩展一次/如果我能正常工作):

<html>
<head>
    <title>Tracking HTML File</title>
    <script language="javascript" type="text/javascript">
        alert("outside the jQuery ready");
        $(function() {
            alert("inside the jQuery ready");
        });
    </script>
</head>

<body>
</body>
</html>

I'm seeing both alert messages in IE (6 & 7) and Firefox (2 & 3). However, I am not able to see the messages in Safari (the last browser that I need to be concerned with - project requirements - please no flame wars).

我在 IE(6 和 7)和 Firefox(2 和 3)中都看到了警报消息。但是,我无法在 Safari 中看到消息(我需要关注的最后一个浏览器 - 项目要求 - 请不要发生冲突)。

Any thoughts on why Safari is ignoring the JavaScript in the trackingCode.htmlfile?

关于为什么 Safari 忽略trackingCode.html文件中的 JavaScript 的任何想法?

Eventually I'd like to be able to pass JavaScript objects to this trackingCode.htmlfile to be used within the jQuery ready call, but I'd like to make sure this is possible in all browsers before I go down that road.

最终,我希望能够将 JavaScript 对象传递给这个trackingCode.html文件,以便在 jQuery 就绪调用中使用,但在我走这条路之前,我想确保这在所有浏览器中都是可能的。

采纳答案by Tony Miller

You are loading an entire HTML page into your div, including the html, head and body tags. What happens if you do the load and just have the opening script, closing script, and JavaScript code in the HTML that you load?

您正在将整个 HTML 页面加载到您的 div 中,包括 html、head 和 body 标签。如果您执行加载并且在加载的 HTML 中只有打开脚本、关闭脚本和 JavaScript 代码,会发生什么情况?

Here is the driver page:

这是驱动程序页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>jQuery Load of Script</title>
        <script type="text/javascript" src="http://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("jquery", "1.3.2");
        </script>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#myButton").click(function() {
                    $("#myDiv").load("trackingCode.html");
                });
             });
         </script>
    </head>
    <body>
        <button id="myButton">Click Me</button>
        <div id="myDiv"></div>
    </body>
</html>

Here is the contents of trackingCode.html:

以下是 trackingCode.html 的内容:

<script type="text/javascript">
    alert("Outside the jQuery ready");
    $(function() {
        alert("Inside the jQuery ready");
    });
 </script>

This works for me in Safari 4.

这在 Safari 4 中对我有用。

Update: Added DOCTYPE and html namespace to match the code on my test environment. Tested with Firefox 3.6.13 and example code works.

更新:添加了 DOCTYPE 和 html 命名空间以匹配我测试环境中的代码。使用 Firefox 3.6.13 测试,示例代码有效。

回答by xtds

$("#images").load(location.href+" #images",function(){
    $.getScript("js/productHelper.js"); 
});

回答by Yannick

A other version of John Pick's solutionjust before, this works fine for me :

之前另一个版本的John Pick 解决方案,这对我来说很好用:

jQuery.ajax({
   ....
   success: function(data, textStatus, jqXHR) {
       jQuery(selecteur).html(jqXHR.responseText);
       var reponse = jQuery(jqXHR.responseText);
       var reponseScript = reponse.filter("script");
       jQuery.each(reponseScript, function(idx, val) { eval(val.text); } );
   }
   ...
});

回答by ryan

I realize this is somewhat of an older post, but for anyone that comes to this page looking for a similar solution...

我意识到这是一篇较旧的帖子,但是对于来到此页面寻找类似解决方案的任何人...

http://api.jquery.com/jQuery.getScript/

http://api.jquery.com/jQuery.getScript/

jQuery.getScript( url, [ success(data, textStatus) ] )
  • url- A string containing the URL to which the request is sent.

  • success(data, textStatus)- A callback function that is executed if the request succeeds.

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});
jQuery.getScript( url, [ success(data, textStatus) ] )
  • url- 包含请求发送到的 URL 的字符串。

  • success(data, textStatus)- 请求成功时执行的回调函数。

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

回答by tim

This doesn't seem to work if you're loading the HTML field into a dynamically created element.

如果您将 HTML 字段加载到动态创建的元素中,这似乎不起作用。

$('body').append('<div id="loader"></div>');
$('#loader').load('htmlwithscript.htm');

I look at firebug DOM and there is no script node at all, only the HTML and my CSS node.

我查看了 firebug DOM,根本没有脚本节点,只有 HTML 和我的 CSS 节点。

Anyone have come across this?

有人遇到过这个吗?

回答by Mohan

I wrote the following jquery plugin for html loading function: http://webtech-training.blogspot.in/2010/10/dyamic-html-loader.html

我为html加载功能编写了以下jquery插件:http: //webtech-training.blogspot.in/2010/10/dyamic-html-loader.html

回答by John Pick

You've almost got it. Tell jquery you want to load only the script:

你已经差不多了。告诉 jquery 你只想加载脚本:

$("#myBtn").click(function() {
    $("#myDiv").load("trackingCode.html script");
});

回答by John Pick

Test with this in trackingCode.html:

在 trackingCode.html 中对此进行测试:

<script type="text/javascript">

    $(function() {

       show_alert();

       function show_alert() {
           alert("Inside the jQuery ready");
       }

    });
 </script>

回答by efreed

I ran into this where the scripts would load once, but repeat calls would not run the script.

我遇到了脚本将加载一次的情况,但重复调用不会运行脚本。

It turned out to be an issue with using .html() to display a wait indicator and then chaining .load() after it.

事实证明,使用 .html() 显示等待指示器然后在其后链接 .load() 是一个问题。

// Processes scripts as expected once per page load, but not for repeat calls
$("#id").html("<img src=wait.gif>").load("page.html");

When I made them separate calls, my inline scripts loaded every time as expected.

当我分别调用它们时,我的内联脚本每次都按预期加载。

// Without chaining html and load together, scripts are processed as expected every time
$("#id").html("<img src=wait.gif>");
$("#id").load("page.html");

For further research, note that there are two versions of .load()

为了进一步研究,请注意 .load() 有两个版本

A simple .load() call (without a selector after the url) is simply a shorthand for calling $.ajax() with dataType:"html" and taking the return contents and calling .html() to put those contents in the DOM. And the documentation for dataType:"html" clearly states "included script tags are evaluated when inserted in the DOM." http://api.jquery.com/jquery.ajax/So .load() officially runs inline scripts.

一个简单的 .load() 调用(url 后没有选择器)只是调用 $.ajax() with dataType:"html" 并获取返回内容并调用 .html() 将这些内容放入 DOM 的简写. 并且 dataType:"html" 的文档明确指出“插入到 DOM 中时会评估包含的脚本标签”。http://api.jquery.com/jquery.ajax/所以 .load() 正式运行内联脚本。

A complex .load() call has a selector such as load("page.html #content"). When used that way, jQuery purposefully filters out script tags as discussed in articles like this one: https://forum.jquery.com/topic/the-load-function-and-script-blocks#14737000000752785In this case the scripts never run, not even once.

一个复杂的 .load() 调用有一个选择器,例如 load("page.html #content")。以这种方式使用时,jQuery 会故意过滤掉脚本标签,如以下文章中所述:https: //forum.jquery.com/topic/the-load-function-and-script-blocks#14737000000752785在这种情况下,脚本永远不会运行,甚至一次。

回答by RCNeil

Tacking onto @efreed answer...

处理@efreed 的答案...

I was using .load('mypage.html #theSelectorIwanted')to call content from a page by selector, but that means it does not execute the inline scripts inside.

我曾经.load('mypage.html #theSelectorIwanted')通过选择器从页面中调用内容,但这意味着它不会执行内部的内联脚本。

Instead, I was able to change my markup so that '#theSelectorIwanted'became it's own file and I used

相反,我能够更改我的标记,使其'#theSelectorIwanted'成为自己的文件,并且我使用了

load('theSelectorIwanted.html`, function() {}); 

and it ran the inline scripts just fine.

它运行内联脚本就好了。

Not everyone has that option but this was a quick workaround to get where I wanted!

不是每个人都有这个选项,但这是一个快速的解决方法,可以到达我想要的地方!