首页 > 解决方案 > javascript打开带有变量的新html

问题描述

我想通过按下此按钮转到“stats.html”,并且我想在第一个站点的“stats.html”代码上写入 var 名称:

<html>
    <head>
    </head>
    <body>
        <script type="text/javascript">  
            function getcube(){  
                var number=document.getElementById("field").value;  
            }  
            function window() {
                var number=document.getElementById("field").value;
            }
        </script>
        <form action="stats.html">
            <input id="field" type="text" name="name" placeholder="Player Name...">
            <input id="button" type="submit" value="SEARCH" onclick="window()">
        </form>
    </body>
</html>

我不知道我应该在“stats.html”中包含什么。

感谢帮助。

标签: javascript

解决方案


一种方法是使用查询参数。

// index.html
<script type="text/javascript">  
  function redirect() {
    const name = document.getElementById("name").value;
    location.href = `stats.html?name=${name}`;
  }
</script>

<input id="name" type="text" name="name" placeholder="Player Name...">
<input id="button" value="Go!" onclick="redirect()">

// stats.html
<script type="text/javascript"> 
  const urlParams = new URLSearchParams(window.location.search);
  const name = urlParams.get('name');
  document.getElementById("name").value = name;
</script>

<input id="name" type="text" name="name" placeholder="Player Name...">

更多信息: 如何在 JavaScript 中获取查询字符串值


推荐阅读