javascript - 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.
解决方案
您需要向 sessionStorage 添加两个参数:键和值。像这样的东西:
sessionStorage.setItem("selectValue", value);
此外,据我所知,如果您使用path/cart.html
在浏览器中打开的本地 html 文件,sessionStorage 无法帮助您;它的范围仅限于页面。如果您通过 localhost 为他们提供服务,您会没事的。
推荐阅读
- git - 从另一个分支或从 master 创建 Git 分支?
- python - 是否可以连接一个类的属性以在 python 中的另一个类中使用?
- common-lisp - 在 Common Lisp 中按名称访问函数参数
- ruby-on-rails - Ruby Hash 包含单个键的额外值
- ssl - 收到此错误:错误!“openssl_certificate”不是 Play 的有效属性
- debugging - 在 PyCharm 中,比较两个调试脚本的值
- python - Pygame 缺少退出模块
- vue.js - 如何在Vue3中做一个简单的倒计时?
- python - 无法合并 Pandas 数据框
- excel - 如何在VBA中的范围内均匀分布已知数字