[英]Using javascript variable in different parts of liquid code
I'm a total noob ... trying to modify the code in my shopify store.我是个菜鸟……试图修改我的 shopify 商店中的代码。
I need to use a javascript variable in a function to display delivery date.我需要在函数中使用 javascript 变量来显示交货日期。
How can I pass the variable between different javascript codes in the liquid file?如何在液体文件中的不同 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>
I'm afraid it does not work that way.恐怕它不会那样工作。 You could do it like you try above, but won't be a clean way of doing it.
你可以像上面那样做,但不会是一种干净的方式。 Instead set your value somewhere in the document where you can read it from, like in an
input
element.而是将您的值设置在文档中您可以从中读取它的某个位置,例如在
input
元素中。
<input type="hidden" name="shippingtime" value="{{ shippingtime }}"/>
Then in JavaScript check the value
of that input
element and handle accordingly.然后在 JavaScript 中检查该
input
元素的value
并进行相应处理。
// Select the input.
const input = document.querySelector('input[name="shippingtime"]');
// Get the value of the input.
const { value } = input;
Whenever you navigate the page you reload everything, including all JS.每当您浏览页面时,您都会重新加载所有内容,包括所有 JS。 But you can store variables with the
Web Storage API
.但是您可以使用
Web Storage API
存储变量。 Either store them in a session with sessionStorage
(stored until browser is closed) or indefinitely with localStorage
.要么将它们存储在
sessionStorage
的会话中(一直存储到浏览器关闭),要么无限期地使用localStorage
。 For this example I'll use the sessionStorage
.对于这个例子,我将使用
sessionStorage
。
// Stores the value.
sessionStorage.setItem('shippingtime', value);
On another page you can check if the storage has an item called shippingtime
.在另一个页面上,您可以检查存储是否有名为
shippingtime
的项目。
const shippingTime = sessionStorage.getItem('shippingtime');
if (shippingTime !== null) {
// Use the shippintTime value here.
console.log(shippingTime);
}
Hope this helps you out.希望这可以帮助你。 If you have any questions or I have been unclear, please let me know.
如果您有任何问题或我不清楚,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.