簡體   English   中英

在 Liquid 代碼的不同部分使用 javascript 變量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM