我是一个菜鸟,正想修改我的shopify商店中的代码。
我需要在函数中使用javascript变量来显示交货日期。
如何在液体文件中的不同JavaScript代码之间传递变量?
{% if shippingtype == 'long' %}
<script> var shippingtime = 'long'; </script>
{% else %}
<script> var shippingtime = 'short'; </script>
{% endif %}
<script>
alert(shippingtime); //and do other stuff with variable
</script>
恐怕那样行不通。您可以像上面尝试的那样进行操作,但是这样做并不是一种干净的方法。而是将值设置在文档中可以读取的位置,例如input
元素中。
<input type="hidden" name="shippingtime" value="{{ shippingtime }}"/>
然后在JavaScript中检查value
该的input
元素和相应的处理。
// Select the input.
const input = document.querySelector('input[name="shippingtime"]');
// Get the value of the input.
const { value } = input;
每当您浏览页面时,都将重新加载所有内容,包括所有JS。但是您可以使用来存储变量Web Storage API
。可以将它们存储在与的会话中sessionStorage
(存储到关闭浏览器之前),也可以将其无限期地存储在localStorage
。在本示例中,我将使用sessionStorage
。
// Stores the value.
sessionStorage.setItem('shippingtime', value);
在另一页上,您可以检查存储中是否有一个名为的项目shippingtime
。
const shippingTime = sessionStorage.getItem('shippingtime');
if (shippingTime !== null) {
// Use the shippintTime value here.
console.log(shippingTime);
}
希望这可以帮助你。如果您有任何疑问或我不清楚,请告诉我。
谢谢,我想会话存储将是前进的道路。昨晚我无法正常工作,但稍后会再试。
我现在正在使用sessionStorage,这就是我需要的,谢谢