Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从JavaScript按submit时如何更改Html页面?_Javascript_Html_Frontend - Fatal编程技术网

从JavaScript按submit时如何更改Html页面?

从JavaScript按submit时如何更改Html页面?,javascript,html,frontend,Javascript,Html,Frontend,我有一个带有文本输入的表单,用户在其中给出自己的名字,还有一个提交输入按钮。当按下按钮时,我想将名称保存到JS中的一个变量中以供以后使用,并将Html页面更改为下一页(下一页是intro.Html,我创建了这个文件,所以这不是问题所在)。我下面的代码不起作用:看起来好像只是刷新了原始页面。请帮忙! 另外,很抱歉代码片段组织得很差,我是StackOverflow新手 var start=document.getElementById('menu-banner-button'); const to

我有一个带有文本输入的表单,用户在其中给出自己的名字,还有一个提交输入按钮。当按下按钮时,我想将名称保存到JS中的一个变量中以供以后使用,并将Html页面更改为下一页(下一页是intro.Html,我创建了这个文件,所以这不是问题所在)。我下面的代码不起作用:看起来好像只是刷新了原始页面。请帮忙! 另外,很抱歉代码片段组织得很差,我是StackOverflow新手

var start=document.getElementById('menu-banner-button');
const toPage2=函数(){
var username=document.getElementById('username')。值;
window.location.pathname=“resources/html/intro.html”;
}
start.onclick=toPage2

MW-主菜单
你好欢迎来到我的世界。
我们叫你什么?

我认为这可能是因为您通常需要执行event.preventDefault(),这样页面就不会刷新


最简单:提交表单并在下一页使用searchParams


你好欢迎来到我的世界。
我们叫你什么?
在intro.html中:

const username = new URL(location.href).searchParams.get("username")
const username = sessionStorage.getItem("username");
如果不是,则如果不想通过服务器,则需要使用窗口存储:

document.getElementById('form1').addEventListener("submit",function(e) {
  e.preventDefault(); // stop submission
  const username = document.getElementById('username').value;
  sessionStorage.setItem("username",username);
  window.location.pathname = "resources/html/intro.html";
})
在intro.html中:

const username = new URL(location.href).searchParams.get("username")
const username = sessionStorage.getItem("username");

这回答了你的问题吗?非常感谢,成功了!但为什么它会自动刷新?这是默认行为吗?是的,这是提交的默认行为。