如何将javascript变量从一个html页面传递到其他html页面

mah*_*esh 1 html javascript jquery href querystringparameter

我有以下代码将example1.html中的变量传递给example2.html,window.location.href中的语法将导航到带有用户名和关键字的example2.html.

example1.html的

<script type="text/javascript">
    var username = ($("#username").val());
    var keyword = ($("#keyword").val());

    $("#button1").click(function(){
         window.location.href = "http://localhost:2757/example2.html";
    });
</script>
Run Code Online (Sandbox Code Playgroud)

Mic*_*ins 5

如果要通过查询字符串参数传递它们,可以执行以下操作:

window.location = "http://localhost:2757/example2.html?username=" + username + "&keyword=" + keyword;
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记在URL中对&符号进行编码,或者使用&amp; 代替&,或者使用window.location = encodeURI(url); (2认同)