要在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函数或变量的脚本
基础教程推荐
- vue中配置mint-ui报css错误问题的解决方法 2023-12-09
- HTML-CSS(五十一)column分栏布局 2023-10-26
- 鼠标悬停图片产生边框的效果实现 2023-12-19
- 基于h5的history改善ajax列表请求体验 2022-10-17
- jQuery实现的点击按钮改变样式功能示例 2023-12-21
- 完美实现CSS垂直居中的11种方法 2022-11-16
- ajax实现改变状态和删除无刷新的实例 2023-02-14
- 手机端 HTML5使用photoswipe.js仿微信朋友圈图片放大效果 2023-12-14
- 深入浅析AjaxFileUpload实现单个文件的 Ajax 文件上传库 2022-12-18
- CSS隐藏页面元素的5种方法 2023-12-20
