gpt4 book ai didi

javascript - 从 iframe 重用 jQuery 对象?

转载 作者:行者123 更新时间:2023-11-30 16:09:18 25 4
gpt4 key购买 nike

我有一个 WYSIWYG 应用程序,它使用 iframediv 转换为编辑器。该应用程序在内部使用 jQueryjQuery UI 作为其核心库。为了扩展应用程序的功能,我正在考虑使用 jQueryjQuery UI,这在我的父 DOM

中不可用

我有两个选择

在我的父 DOM 中加载库。从 iframe 本身获取库并开始扩展应用程序,即 jQuery = window.frames[0]。 jQuery.

后者使我免于将其加载到我的父级 DOM,但是我遇到了对话框选择菜单无法按预期工作的问题。它根本不显示选项。代码是这样的:

// Here I chose both jQuery from parent and 
// jQuery = window.frames[0].jQuery
div = jQuery("<div id="dialog" title="Dialog"></div>")
div.append("<select><option>Foo</option>Bar<option></option></select>")
jQuery("body").append(div)
div.dialog{appendTo:editorID} //Editor is in iframe

有谁知道当你这样做时会发生什么 jQuery = window.frames[0].jQuery?这个 jQuery 对象会一直操纵 iframe DOM 而不是父 DOM 吗?或者 jQuery 是否可以与新的 DOM 一起正常工作。

最佳答案

只要满足以下条件,就可以将内容从 iframe 复制到父页面:

父页面(托管 iframe 的页面)和子页面(iframe 内的页面)都满足 same-origin policy :

Both pages must have matching:

  • Protocol (ex. http: and https: would fail)
  • Subdomain (ex. http://app.domain.com and http://www.domain.com fails)*
  • Domain (goes without saying apples.com and oranges.org fails)
  • Port (ex. https://www.generic.com:8080 and https://www.generic.com:8088 fails)

*有办法解决这个问题

在我脑海中,我知道 2 个传输节点的 JavaScript 方法:

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode()) before they can be inserted into the current document. The use of node.cloneNode() is discouraged when cloning from an external document on to the current document.

第一个演示使用 importNode()在 iframe 加载后将外部页面的主体复制到 iframe 并将其附加到 <section> (可以使用任何 block 元素)。

第二个演示使用 importNode()在点击事件上。要查看结果,请单击按钮,然后向下滚动。

注意:此程序适用于<script> block 也是如此。

http://plnkr.co/edit/yUW2CYqDqrvEq5fT1ty6?p=preview

JavaScript

iFrame1.onload = function() {
bodySnatcher('#iFrame1', '#display');
}
var btn1 = document.getElementById('btn1');
btn1.addEventListener('click', function() {
bodySnatcher('#iFrame2', '#display');
}, false);

function bodySnatcher(iframe, parent) {
var iFrame = document.querySelector(iframe);
var iBody = iFrame.contentWindow.document.getElementsByTagName("body")[0];
var imported = document.importNode(iBody, true);
document.querySelector(parent).appendChild(imported);
}

关于javascript - 从 iframe 重用 jQuery 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36513952/

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