[英]javascript / jquery using a variable to reference different parts of a json/xml object
[英]Using javascript variable in different parts of liquid code
我是个菜鸟……试图修改我的 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 中检查该input
元素的value
并进行相应处理。
// 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);
}
希望这可以帮助你。 如果您有任何问题或我不清楚,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.