首页 > 解决方案 > Passing Variables from one page to another

问题描述

Im trying to pass a value from one page for a product to another page for the cart.

I've tried a few different options but haven't managed to come up with any solution.

I'm new to html and javascript so need a simple solution if thats possible so that I can understand.

Product Page

<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>

Cart page

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

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

I would need to value from the drop down to be passed to the cart page to work out the value for all the users products selected.

标签: javascripthtmlvariables

解决方案


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

sessionStorage.setItem("selectValue", value);

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


推荐阅读