【问题标题】:Using javascript variable in different parts of liquid code在液体代码的不同部分使用 javascript 变量
【发布时间】:2020-02-05 21:50:27
【问题描述】:

我是个菜鸟……试图修改我的 shopify 商店中的代码。

我需要在函数中使用 javascript 变量来显示交货日期。

如何在 Liquid 文件中的不同 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>

【问题讨论】:

  • 很遗憾,您没有为您的问题提供足够的背景信息,以便有人正确回答。什么时候需要显示?您需要在哪里显示它?最初的价值从何而来?我不熟悉shopify,但通常最好的方法是从服务器(例如数据库)将其加载到页面上。
  • 运输时间变量是在购物车页面上创建的。当用户在购物车中添加或删除东西时,它将根据库存水平而变化。因此,它应该在页面加载后根据用户输入进行更改。它应该显示在购物车底部靠近付款按钮的位置..

标签: javascript shopify liquid


【解决方案1】:

恐怕它不会那样工作。你可以像上面尝试的那样做,但不会是一种干净的方式。而是将您的值设置在文档中您可以从中读取的某个位置,例如在 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);
}

希望这对您有所帮助。如果您有任何问题或我不清楚,请告诉我。

【讨论】:

  • 谢谢,我想会话存储将是前进的方向。我昨晚无法让它工作,但稍后会再试一次。
  • 我的 sessionStorage 现在可以工作了,这正是我所需要的,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
  • 2011-07-22
  • 2020-06-15
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
相关资源
最近更新 更多