繁体   English   中英

将变量从一页传递到另一页

[英]Passing Variables from one page to another

我试图将产品的一个页面的值传递到购物车的另一个​​页面。

我尝试了一些不同的选项,但没有设法提出任何解决方案。

我是 html 和 javascript 的新手,所以如果可能的话,我需要一个简单的解决方案,以便我能理解。

产品页面

<label for="exampleFormControlSelect1">Example select</label>
<div>
   <select class="form-control" id="Selected">
       <option value='1'>1</option>
       <option value='2'>2</option>
       <option value='3'>3</option>
       <option value='4'>4</option>
       <option value='5'>5</option>
   </select>
</div>
<button id='btn' type="button" class="btn btn-secondary">Add To Cart</button>

<script type="text/javascript">
   var value=0;

   function send_selected(){
      var selector = document.getElementById('Selected');
      var value = selector[selector.selectedIndex].value;

      sessionStorage.setItem(value);
   }

   document.getElementById('btn').addEventListener('click',send_selected);
</script>

购物车页面

<script type="text/javascript">
   var value = sessionStorage.getItem("value");
   document.getElementById('display').innerHTML = value;
</script>

<body>
  <div id="display"></div>
</body>

我需要将下拉列表中的值传递到购物车页面,以计算出所有用户选择的产品的值。

您需要向 sessionStorage 添加两个参数:键和值。 像这样的东西:

sessionStorage.setItem("selectValue", value);

此外,据我所知,如果您使用在浏览器中打开的本地 html 文件(如path/cart.html ),那么 sessionStorage 无法帮助您; 它的范围仅限于页面。 如果您通过 localhost 为他们提供服务,您会没事的。

如果此页面有不同的 url,您可以使用查询参数来完成: https ://en.wikipedia.org/wiki/Query_string

按浏览器存储方式:

正如@Ferenc 所说,会话存储的 setItem 方法有两个参数。

sessionStorage.setItem("selectedItem","value");

或者你可以使用 sessionStorage["selectedItem"] = "value";

要在浏览器中的任何其他位置检索值,您可以使用getItem()方法,也可以使用类似值访问方法的数组,即

var value = sessionStorage["selected"];

但我建议您使用 localStorage 而不是 sessionStorage,因为它的范围比 sessionStorage 范围大。 您可以在此处阅读不同的黑白会话存储和本地存储。
注意:您可以通过查看浏览器控制台来检查您的 javascript 代码中的错误(现在当您使用单个参数调用 getItem 方法时会发生这种错误)。

按查询参数:

好吧,如果您不使用任何服务器端语言,则不推荐使用此方法。 即Java、PHP 等。在这种情况下,您在url 中附加查询字符串。 IE

http://www.url.com?value=selected

要阅读如何使用 javascript 访问查询参数,请参阅此问题。

添加到第一个 HTML 文件中对我有用:

where_from = document.getElementById("where_from").value;
sessionStorage.setItem("pass_to_other_form", where_from);

然后到第二个 HTML 文件:

var from_other = sessionStorage.getItem("pass_to_other_form");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM