search
HomeWeb Front-endJS TutorialMethods and precautions for calling JS in the child parent class window in iframe_javascript skills

1. Foreword

My page uses EasyUI’s pop-up window with an iframe embedded in it.

First: When the parent window opens the child window, it is an iframe subpage that adds user information. After clicking Save, the child window iframe calls the function closeAddWindow() method of the parent window, allowing the parent window to close the newly added page;

Second: The parent window opens an iframe sub-window to set user permissions. First, opening this sub-window will load all existing permissions in the database table, and then the sub-window needs to splice the loaded permission information into html Append to an ID For

, there is a problem here that after the parent window opens the child window and loads all permissions, it is impossible to append html to the table with id="tb". This reason is very Simple, because after the parent window calls the child window to load all the permission information, the table element is not found because the child page has not been completely loaded. The handling of this situation is also introduced here. Register an onload event for the iframe, and wait until the loading is completed. Then call the append method.

Okay, that’s it, let’s take a look at more examples! ! ~~~~~~(*^__^*) Hee hee...

2. iframe child and parent window method calls

2.1 Grammar usage

1. Parent window embedded iframe

Copy code The code is as follows:


2. The parent window calls the child window method

Copy code The code is as follows:

myFrame.window.sonMethod();

3. The child window calls the parent window method

Copy code The code is as follows:

parent.fatherMethod();

4. Browser-compatible iframe loading completion method

 if (myFrame.attachEvent) {
      myFrame.attachEvent("onload", function () {
        alert("兼容IE加载的加载方法");
      });
    } else {
      myFrame.onload = function () {
        alert("兼容其他浏览器加载方法");
      };
    }

2.2 Grammar code

Father.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>
</head>
<body>
  <div>我是父窗口内容</div>
  <div><input type="button" id="btnFather" value="调用子窗口方法" /></div>
  <br />
  <br />
  <br />
  <iframe id='myFrame' name="myFrame" src="FChild.html" width='100%' height='100%' frameborder='0'></iframe>
  <script type="text/javascript">
    document.getElementById("btnFather").onclick=function () {
      myFrame.window.sonMethod();
    }
    function fatherMethod() {
      alert("父窗口方法!");
    }
    if (myFrame.attachEvent) {
      myFrame.attachEvent("onload", function () {
        alert("兼容IE加载的加载方法");
      });
    } else {
      myFrame.onload = function () {
        alert("兼容其他浏览器加载方法");
      };
    }
  </script>
</body>
</html>

FChild.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title></title>
</head>
<body>
  <div style="border:1px solid red;"> 我是子窗体内容</div> 
   <div > <input type="button" id="btnSon" value="调用父窗口方法" /></div> 
   <script type="text/javascript">
     document.getElementById("btnSon").onclick = function () {
       parent.fatherMethod();
     }
     function sonMethod() {
       alert("子窗口方法!");
     }
  </script>
</body>
</html>

3. When to use myFrame.onload or myFrame.attachEvent

The easyui framework front-end framework is used here

<div id="divRoleUsers" title="设置用户角色" class="easyui-window" closed="true" collapsible="false" minimizable="false" maximizable="false" style="width: 140px; height: 250px; padding: 5px;">
   </div>
 <div > <input type="button" id="btn" value="设置用户角色" /></div> 
 <script type="text/javascript">
 $("#btn").click(function () {
showSetUserRoleWindow();
});
    //设置用户角色
    function showSetUserRoleWindow() {
      var getSelections = $("#tt").datagrid("getSelections");
      if (getSelections.length > 1 || getSelections.length == 0) {
        $.messager.alert("错误提示", "请选中一行数据!", "error");
        return false;
      }
      var data = getSelections[0]; //获取选中的一行所有json的数据
      //if ($("#divRoleUsers #iframe").length != 0) {
      //  $("#divRoleUsers #iframe").remove();
      //}
      //  $('#divRoleUsers').append("<iframe id='iframe' name='iframe' src='RoleUsers_Update.aspx&#63;UserID=" + data.UserID + "' width='100%' height='100%' frameborder='0'></iframe>");
      //错误做法!:上面src='RoleUsers_Update.aspx&#63;UserID=" + data.UserID + "'   这里通过拼接参数iframe的src,
      //然后通过子窗口 parent.document.getElementById("iframe").getAttribute("src");//获取父窗体iframe的src 发现根据获取不到UserID的值,为null,也是因为加载顺序先后的问题,导致我要用给iframe注册onload事件后才能获取到我需要的结果
      //if (myframe.attachEvent) {
      //  myframe.attachEvent("onload", function () {
      //    alert("Local iframe is now loaded.");
      //    myframe.window.loadAllRole();
      //  });
      //} else {
      //  myframe.onload = function () {
      //    alert("Local iframe is now loaded.");
      //    myframe.window.loadAllRole();
      //  };
      //}
      if ($("#divRoleUsers #myframe").length != 0) {   //这一步是必须的!!!,因为不加这一句下面onload绑定事件只执行一次,我需要每次加载完iframe都调用一次子窗口的方法!
        $("#divRoleUsers #myframe").remove();
      }
      $('#divRoleUsers').append("<iframe id='myframe' name='myframe' src='RoleUsers_Update.aspx' width='100%' height='100%' frameborder='0'></iframe>");
      if (myframe.attachEvent) {
        myframe.attachEvent("onload", function () {
          myframe.window.loadAllRole(); 
          myframe.window.loadUserRole(data.UserID);
        });
      } else {
        myframe.onload = function () {
          myframe.window.loadAllRole();     //调用子窗口iframe里面的方法加载所有的角色checkbox
          myframe.window.loadUserRole(data.UserID);   //接着传递用户ID过去给子窗口的方法,给用户拥有的角色设置checkbox选中
        };
      }
      $('#divRoleUsers').window('open');
    }
  </script>

4. Let’s summarize a few key points

When calling the parent-child window method, pay attention to the order of loading to get the desired results. If you encounter problems, you can often use alter() to test or monitor the browser's developer tools

The above content is the method and precautions for calling JS in the sub-parent class window of iframe in this article. I hope you like it.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.