![](/img/trans.png)
[英]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.