使用Javascript重定向HTML中的路由



我有3个html文件要链接在一起。这三个文件分别是button.htmloption1.htmloption2.html,并且所有三个文件都存储在一个src文件夹中。

button.html是一个简单的网页,包含两个按钮:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script type="text/javascript">
document.getElementById("option1").onclick = function () {
location.href = "./option1.html";
};
document.getElementById("option2").onclick = function () {
location.href = "./option2.html";
};
</script>
</head>
<body>
<button type="button" id="option1">Option 1</button>
<button type="button" id="option2">Option 2</button>
</body>
</html>

另外两个.HTML文件是常规页面,每个页面都有不同的内容。

<!DOCTYPE html>
<html>
<head>
<title>Option 1/2</title>
</head>
<body>
// different data contained for option1.html and option2.html
<h1>Heading for Option 1 or 2</h1>
<p>Paragraph for Option 1 or 2</p>
</body>
</html>

我不确定我做错了什么,但即使每个按钮都有onClick((函数,按钮也不会链接到其他HTML文件。我想知道我是否应该在这两个HTML文件的标题中有某种链接标记。此外,我不太确定location.href行在button.html文件的脚本标记中的作用。我刚刚在网上找到了一些资源来尝试一下。

此外,我需要只使用Vanila Javascript、HTML和CSS来完成这项工作。

请帮帮我。谢谢

更新:我相信这会奏效。请看,首先,始终在结束正文标记之前添加脚本标记。原因是,如果它所查找的DOM元素没有被呈现,那么代码将无法工作。

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button type="button" id="option1">Option 1</button>
<button type="button" id="option2">Option 2</button>
<script type="text/javascript">
document.getElementById("option1").onclick = function() {
location.href = "./option1.html";
};
document.getElementById("option2").onclick = function() {
location.href = "./option2.html";
};
</script>
</body>
</html>

您需要在关闭body标记之前添加script标记。

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button type="button" id="option1">Option 1</button>
<button type="button" id="option2">Option 2</button>
<script type="text/javascript">
document.getElementById("option1").onclick = function () {
location.href = "./option1.html";
};
document.getElementById("option2").onclick = function () {
location.href = "./option2.html";
};
</script>
</body>
</html>

有一种叫做同源策略的东西https://javascript.info/cross-window-communication#can-t-get-but-can-set,这可能会受到location.href的影响,如果您在本地存储中预览文件,而不是在web服务器中预览文件。尝试将其更改为location="option.html";等等,移除hrer

或者,你可以制作一个不可见的标签,设置hrer,然后用JS 点击它

var a=document.createElement("a"(;a.href=";option1.html";;a.点击((;

然后把它放在你的onclick函数中,

编辑另一件事刚刚实现

脚本标记在html的头部,但按钮在主体中,所以尝试将脚本标记复制到主体标记的底部,在按钮下面,或者用window.onload=function {/*other code goes here*/}包围两个onclick函数

最新更新