要在JavaScript中调用其他页面的函数或变量,有以下两种方法:
要在JavaScript中调用其他页面的函数或变量,有以下两种方法:
1. 使用window.opener对象
当在一个页面中用window.open打开另一个页面时,这个被打开的页面就可以使用window.opener来访问打开它的页面。所以,我们可以利用这个特性来调用父页面的函数或变量。
父页面示例代码:
<!DOCTYPE html>
<html>
<head>
    <title>父页面</title>
</head>
<body>
    <button onclick="openNewPage()">打开子页面</button>
    <script>
        var message = "Hello World!";
        function showMessage() {
            alert(message);
        }
        function openNewPage() {
            window.open("child.html");
        }
    </script>
</body>
</html>
子页面示例代码:
<!DOCTYPE html>
<html>
<head>
    <title>子页面</title>
</head>
<body>
    <button onclick="window.opener.showMessage()">调用父页面函数</button>
    <button onclick="alert(window.opener.message)">调用父页面变量</button>
</body>
</html>
在子页面中,我们可以直接使用window.opener来访问父页面的函数和变量。示例代码中,在子页面中点击调用父页面函数按钮时,会将执行showMessage函数,弹出"Hello World!"的提示窗口;在点击调用父页面变量按钮时,会弹出"Hello World!"的提示窗口。
2. 使用LocalStorage
LocalStorage是浏览器提供的本地存储机制,我们可以利用LocalStorage来在两个页面间传递数据,包括函数和变量。
示例代码:
<!DOCTYPE html>
<html>
<head>
    <title>页面1</title>
    <script>
        var message = "Hello World!";
        function showMessage() {
            alert(message);
        }
        function saveMessage() {
            localStorage.setItem("message", message);
        }
    </script>
</head>
<body>
    <h1>页面1</h1>
    <button onclick="showMessage()">显示消息</button>
    <button onclick="saveMessage()">保存消息到LocalStorage</button>
    <a href="page2.html">进入页面2</a>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>页面2</title>
    <script>
        function showMessageFromLocalStorage() {
            alert(localStorage.getItem("message"));
        }
    </script>
</head>
<body onload="showMessageFromLocalStorage()">
    <h1>页面2</h1>
    <button onclick="window.location.href='page1.html'">返回页面1</button>
</body>
</html>
在页面1中,我们定义了一个变量message和一个函数showMessage,并且提供了一个保存消息到LocalStorage的函数saveMessage。在页面2中,我们定义了一个从LocalStorage中读取消息并弹出提示框的函数showMessageFromLocalStorage,因为这个函数要在页面加载时就执行,所以我们使用了onload事件。
当在页面1中点击保存消息按钮时,将会把变量message保存到LocalStorage中。当点击进入页面2按钮时,跳转到页面2,此时页面2的onload事件将会执行showMessageFromLocalStorage函数,从LocalStorage中读取message变量并弹出提示框。
以上两种方法都能够实现在JavaScript中调用其他页面的函数和变量,不同的是使用window.opener需要在父子页面中建立起关系,而使用LocalStorage则不受页面之间的关系限制。选择哪一种方法取决于具体场景的需求。
本文标题为:javascript 调用其他页面的js函数或变量的脚本
				
        
 
            
        基础教程推荐
- 浅析canvas元素的html尺寸和css尺寸对元素视觉的影响 2024-04-26
 - CSS3的几个标签速记(推荐) 2024-04-07
 - Ajax实现动态加载数据 2023-02-01
 - this[] 指的是什么内容 讨论 2023-11-30
 - 浅谈Vue2和Vue3的数据响应 2023-10-08
 - 基于Vue制作组织架构树组件 2024-04-08
 - 关于文字内容过长,导致文本内容超出html 标签宽度的解决方法之自动换行 2023-10-28
 - vue离线环境如何安装脚手架vue-cli 2025-01-19
 - JS前端广告拦截实现原理解析 2024-04-22
 - js禁止页面刷新与后退的方法 2024-01-08
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				