2014-11-22 71 views
0

我在Shopify中的页面模板中使用链接列表,并且需要将它的长度传递给javascript代码片段。我不知道该怎么做。在Shopify液体中将页面形式的值传递给javascript

页面模板包括此行:

{% assign linklist = linklists['link-list-1'] %} 

和页面包括带有ID的形式=“提交表”类似这样的代码:

<form> 
    <input type="submit" value="Add..." id="submit-table"/> 
     ... 
</form> 

首先,我需要的形式包含链接列表长度的值。不知道该怎么做。

然后,我需要将该长度值传递给此脚本(这是一个片段)。另外,不知道如何做到这一点。

<script type="text/javascript" charset="utf-8"> 
//<![CDATA[ 
// Including jQuery conditionnally. 
if (typeof jQuery === 'undefined') { 
    document.write({{ "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" | script_tag | json }}); 
    document.write('<script type="text/javascript">jQuery.noConflict();<\/script>'); 
} 
//]]> 
</script> 

<script> 

$(document).ready(function() { 
    $("#quantity-0").focus();  
    $("#submit-table").click(function(e) {  
     e.preventDefault(); 
     var toAdd = new Array(); 
     var qty; 
     //I need the link list length value here 
     for(i=0; i < length; i++){ 

      toAdd.push({ 
       variant_id: $("#variant-"+i).val(),   
       quantity_id: $("#quantity-"+i).val() || 0 
      }); 
     } 
     function moveAlong(){ 
      //I need the link list length value here 
      if (toAdd.length) { 
       var request = toAdd.shift(); 
       var tempId= request.variant_id; 
       var tempQty = request.quantity_id; 
       var params = { 
        type: 'POST', 
        url: '/cart/add.js', 
        data: 'quantity='+tempQty+'&id='+tempId, 
        dataType: 'json', 
        success: function(line_item) { 
         //console.log("success!"); 
         moveAlong(); 

        }, 
        error: function() { 
         //console.log("fail"); 
         moveAlong(); 

        } 
       }; 
       $.ajax(params); 
      } 
      else {    
       document.location.href = '/cart'; 
      } 
     }; 
     moveAlong(); 
    }); 
}); 
</script> 

的脚本包含在我的theme.liquid代码像这样:

{% include 'order-form-script' %} 

参考文献:

tetchi博客»Shopify教程:如何创建一个订单
http://www.tetchi.ca/shopify-tutorial-order-form/#comment-10129

https://gist.githubusercontent.com/Tetsuro/2932935/raw/568ccb0574f46eb450e298ab2ccb800e673d8fa2/jquery.order-form.js.liquid

https://gist.githubusercontent.com/Tetsuro/2932738/raw/7c0c5aea3cd59b35194f61e2c6c0b1c7f852f9fb/page.order-form.liquid

回答

1

首先,我需要表单来包含链接列表的长度值。

是这样的吗?

<form> 
    <input type="submit" value="Add..." id="submit-table" /> 
    <input type="hidden" id="linklist-length" name="linklist-length" value="{{ linklists.link-list-1.links.size }}" /> 
    ... 
</form> 

然后我需要通过该长度值给该脚本(这是一个片段)。

访问该值通过ID(或者,如果你想更具体的选择,see here):

var length = $("#linklist-length").val(); 
+0

凡在脚本你建议分配给'VAR length'应该放在哪里?立即在'$(document).ready(function(){'? – MountainX 2014-11-22 07:01:12

+0

')行之后,就在你需要使用它的地方,它看起来像下面的'var qty;' – 2014-11-22 07:52:54

+0

谢谢。 – MountainX 2014-11-22 08:47:23