gpt4 book ai didi

javascript - 将 JavaScript 动态加载到 Div 中

转载 作者:行者123 更新时间:2023-11-29 20:13:23 25 4
gpt4 key购买 nike

我需要将 JavaScript 代码(我无法控制)从 URL 加载到 div 中。 JavaScript 代码是一堆 document.write() 语句。一旦 document.write() 语句执行完毕,我需要使用 jQuery 或 JavaScript 从 div 中提取生成的文本,并将该文本用于其他用途。目前,我正在执行以下操作以将 JavaScript 加载到 div 中:

    $('body').append('<div id="mydiv" style="display: none"></div>');
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
$('#mydiv').append(script);

我怎么知道 document.write 语句何时完成执行,我可以安全地从 div 中提取文本并使用它?或者,有更好的方法吗?

最佳答案

你可以设置一个只有这个的 html 页面(在这个例子中它被称为 test2.html ):

<script type="application/javascript" src="<url of JavaScript>.js"></script>

然后您可以将此页面加载到 iframe 中的 DOM 中并附加 load加载完成后获取页面内容的事件处理程序。然后,此示例还删除了 <iframe>来自 DOM:

$(function () {

//append the iframe onto the body, then select it and attach an event handler for the `load` event
$('body').append('<iframe id="myiframe" style="display: none"></iframe>').children('iframe').on('load', function () {

//set the html of the `mydiv` element to the body of the loaded page (test2.html)
$('#mydiv').html($(this).contents().children().children('body').html());

//remove the iframe from the DOM
$(this).remove();

//set the source of the iframe after the `load` event handler is setup to make sure it fires properly
}).attr('src', 'test2.html');
});

这是一个演示:http://apexeleven.com/stackoverflow/document.write/test.html

请注意 .on()是 jQuery 1.7 中的新内容,与 .bind() 相同在这种情况下。

关于javascript - 将 JavaScript 动态加载到 Div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8460306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com