When developing web applications, it is often necessary to execute a method in a parent page from one page. jQuery is a powerful JavaScript library that helps us achieve this goal easily.
In this article, we will introduce how to use jQuery to execute parent page methods. Below, we will explain it in detail in the following parts:
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> function displayMessage(){ alert("Hello from parent page!"); } </script> </head> <body> <a href="child.html" target="_blank">Open Child Page</a> </body> </html>
In this example, we define a method named "displayMessage()", which is used to pop up a dialog box and display A simple message. We will call this method in the child page.
$(document).ready(function(){ var parentWindow = window.parent; });
In this example, we use jQuery’s document.ready() method. This method waits until the entire page is loaded before executing. We store the obtained parent page reference in a variable parentWindow.
$(document).ready(function(){ var parentWindow = window.parent; parentWindow.displayMessage(); });
In this example, we call the displayMessage() method in the parent page. We get a reference to the parent page by accessing the window.parent property passed to the parent window. We then use this reference to call methods in the parent page.
In the parent page:
<html> <head> <title>Parent Page</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> function displayMessage(){ alert("Hello from parent page!") } </script> </head> <body> <button onclick="window.open('child.html','_blank')">Open Child Page</button> </body> </html>
In the child page:
$(document).ready(function(){ var parentWindow = window.opener; parentWindow.displayMessage(); });
In this example, we use window.open( ) method opens a subpage named child.html. When the user clicks a button on the parent page, the child page is opened and the code in the child page is immediately called.
In the child page, we use the window.opener property to get a reference to the parent window. Through this reference we can access any method or property on the parent page. In this example, we call the displayMessage() method on the parent page through the parent page reference.
Summary
When developing web applications, we often need to call methods in the parent page from the child page. By using jQuery we can easily achieve this goal. In this article, we have introduced two methods through which we can easily call methods from the parent page in the child page.
The above is the detailed content of jquery executes parent page method. For more information, please follow other related articles on the PHP Chinese website!