Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

第 126 期(W3C 标准-JavaScript):iframe父子通信 #129

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

在目前 SPA 一统前端半壁江山的背景下,iframe 这种黑魔法已经很少见了,不过在一些多页面的老项目中仍然有它的一席之地。使用 iframe 比较常见的场景是需要在父窗口中使用 iframe 中的元素,或者在 iframe 中使用父窗口中的元素。

在父窗口中获取 iframe 中的元素

  • 方法1:

    window.frames['iframe的name值'];  // 后接 iframe 中的元素选择器
    
    // 示例:
    window.frames['iframe1'].document.getElementById('btn');  
  • 方法2:

    document.getElementById('iframe的id').contentWindow;  // 后接 iframe 中的元素选择器
    
    // 示例:
    document.getElementById('iframe1').contentWindow.document.getElementById('btn');
  • 方法3:

    $('#iframe的id').contents().find('iframe中的元素选择器');
    
    // 示例:
    $('#iframe1').contents().find('#btn');

在 iframe 中获取父窗口的元素

  • 方法1:

    window.parent.document;  // 后接父级中的元素选择器
    
    // 示例:
    window.parent.document.getElementById('btn');  
  • 方法2:

    $('iframe中的元素选择器', document.frames('frame的name').document);
    
    // 示例:
    $('#btnOk', document.frames('iframe').document);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.