题意:在 Shopify Liquid 中将值从页面表单传递到 JavaScript。
问题背景:
I am using a link list in a Page template in Shopify and I need to pass the length of it to a javascript Snippet. I'm not sure how to do it.
我在 Shopify 的页面模板中使用了链接列表,我需要将其长度传递给一个 JavaScript 片段。我不确定该怎么做。
The page template includes this line:
页面模板包括以下行:
{% assign linklist = linklists['link-list-1'] %}
And the page includes a form with id="submit-table" similar to this code:
页面包含一个 id 为 "submit-table" 的表单,类似于以下代码:
<form>
<input type="submit" value="Add..." id="submit-table"/>
...
</form>
First, I need the form to contain the value of the length of the link list. Not sure how to do that.
首先,我需要表单包含链接列表的长度值。不确定该怎么做。
Then I need to pass that length value to this script (which is a Snippet). Also, not sure how to do that.
然后我需要将该长度值传递给这个脚本(这是一个片段)。同样,不确定该怎么做。
<script type="text/javascript" charset="utf-8">
//<![CDATA[
// Including jQuery conditionally.
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>
The script is included in my theme.liquid code as so:
该脚本在我的 theme.liquid 代码中包含如下:
{% include 'order-form-script' %}
References: 引用
tetchi blog » Shopify Tutorial: How to Create an Order Form
tetchi 博客 » Shopify 教程:如何创建订单表单
http://www.tetchi.ca/shopify-tutorial-order-form/#comment-10129
问题解决:
First, I need the form to contain the value of the length of the link list.
Something like this?
像这样吗?
<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>
Then I need to pass that length value to this script (which is a Snippet).
Access the value via id (or if you want a more specific selector, see here):
通过 ID 访问该值(或者如果你想要更具体的选择器,请参见这里):
var length = $("#linklist-length").val();