首页 > 解决方案 > 将外部 Javascript 嵌入到 Shopify Liquid 文件中以编辑特定的 div

问题描述

第一次在这里发海报。总的来说,我对shopify和计算机科学还是很陌生,所以请多多包涵。

我正在尝试更新横幅,使其在 3 条短信之间轮换。这是我写的 JS 和 HTML。请注意,JS 文件位于 assets 下。

    var banner = document.getElementById("discountbanner");
    setInterval(bannerupdate, 3000);

    function bannerupdate(){
      for(i=1; i != 0; i++)
      {
        switch(i%2){
          case 0:
              banner.innerHTML = "Preorder now for 10% off!";
              break;
          case 1:
              banner.setAttribute("href", "xyz.com");
              banner.innerHTML = "Buy More, Save More: Save up to 30% today!";
              break;
          case 2:
            banner.innerHTML = "Free Shipping on orders of $750+";
            break;
        }
       }
    }
         <div id="discountbanner">
            {% assign pricegoal = cart.items_subtotal_price | divided_by: 100 %}
            {% if pricegoal == 0 %}
                <!--embed JS here-->
             {% elsif pricegoal < 3000 %}
           <a href="xyz.com" title="Click here to learn more!">Spend only ${{ 3000 | minus: pricegoal }} more to save 20%!</a>
            {% elsif pricegoal == 3000 %} 
           <a href="xyz.com" title="Click here to learn more!">You saved 20% on this order! Spend an extra $1500 and save an extra 10%!</a>
            {% elsif pricegoal > 3000 and pricegoal < 4500 %}
           <a href="xyz.com" title="Click here to learn more!">You've saved 20%! Spend only ${{ 4500 | minus: pricegoal }} more to save 30%!</a>
            {% elsif pricegoal > 4500 %}
            You got 30% off your order!
            {% endif %}
          </div>

最终目标是让横幅仅在客户未向其购物车中添加任何内容时旋转。{{'banner.js' | asset_url | script_tag}} 当我使用以及 嵌入 js 时 <script src = "{{'banner.js | asset_url | script_tag}}"></script>

后者似乎不起作用,尽管前者会导致无限循环,理论上它应该这样做,但这会导致页面无限加载并且永远不会显示其余内容。

此外,即使我内联了 js,它仍然没有正确更新。关于如何解决这个问题的任何想法?

我猜这与js有关。

标签: javascripthtmlshopifyliquid

解决方案


看来您的 JS 代码不正确。

var i = 0;
var textArray = [
"Preorder now for 10% off!",
"Buy More, Save More: Save up to 30% today!",
"Free Shipping on orders of $750+"
];

 setInterval(()=>{
  banner.innerHTML = textArray[i%3];
  i++;
 }, 3000);
     

推荐阅读