【问题标题】:Persistent variable on iframe?iframe 上的持久变量?
【发布时间】:2011-09-25 11:41:40
【问题描述】:

我有一个动态创建的<div>,它包含一个<iframe><iframe> 可能会自行关闭,此时 <div> 会被移除。

到目前为止我有:

var div = document.createElement('div'), ifr = document.createElement('iframe');
// some styles and stuff here, including ifr.src
ifr.contentWindow.container = div; // Note that domains are the same

// within the iframe's code, possibly a "close" link or after completing an operation
container.parentNode.removeChild(container);

它有效。但前提是 iframe 中的页面是开始时的页面。如果单击链接到另一个页面,则不再定义 window.container

我知道我可以使用window.name 将数据持久存储到窗口,但它仅限于可以序列化的数据。据我所知,除了为它分配一个 ID 并存储它之外,你不能序列化一个 DOM 节点。我想避免这种任意的 ID,所以如果有人能提出更好的解决方案,我将不胜感激。

【问题讨论】:

    标签: javascript iframe persistent-data


    【解决方案1】:

    使用此代码:

    //At the frame:
    var parentFrames = parent.document.getElementsByTagName("iframe");
    for(var i=parentFrames.length-1; i>=0; i--){
        if(parentFrames[i].contentWindow == window) {
            parentFrames[i].parentNode.removeChild(parentFrames[i]); //Removes frame
            //Add an extra `.parent` at each side of the expression to remove the `div`.
            break;
        }
    }
    

    【讨论】:

    • 啊,是的。我已经在我的代码的其他地方做了类似的事情,不知道为什么我不认为在这里应用它:D 将对其进行测试,并让你知道。
    • 我没有解释代码,因为我假设你在 JS 编程方面已经相当先进了。如果部分代码不清楚,请随时要求澄清。
    【解决方案2】:

    加载到<iframe> 的页面可以使用“window.parent”来访问包含页面。因此,与其在<iframe> 中保留一些“神奇”引用,不如将其保留在包含页面上并让“子”页面查找它。

      function closeMe() { // inside the iframe page
        window.parent.frameContainer.removeChild(window.parent.removableFrame);
      }
    

    除了“parent”之外,“window”的“top”属性在有一系列窗口(框架)长于一个步骤时引用最顶层的上下文(因此,@987654325 中的 <iframe> @ 等)。

    【讨论】:

    • 解决方案有效,但前提是存在这样的<iframe>。如果有两个或更多,如何判断关闭哪个容器?
    • 我认为父 iframe 的“contentWindow”应该是 == iframe 的窗口。我可以用 jsfiddle 检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2011-12-11
    相关资源
    最近更新 更多