我正在使用Shopify,并且使用当前代码,我希望根据用户在下拉菜单中的选择将用户重定向到正确的URL。
我为下拉菜单编写了以下代码:
<ul class="clearfix filters">
<li class="clearfix filter">
<label>Shop by color</label>
<select class="coll-filter">
<option value="/collections/all">All</option>
{% for col in collections %}
<option value="{{ col.url }}"{% if collection.handle == col.handle %}selected="selected"{% endif %}>{{ col.title }}</option>
{% endfor %}
</select>
</li>
</ul>
下面是上面下拉菜单的脚本(集合类似于类别):
<script>
Shopify.queryParams = {};
if (location.search.length) {
for (var aKeyValue, i = 0, aCouples = location.search.substr(1).split('&'); i < aCouples.length; i++) {
aKeyValue = aCouples[i].split('=');
if (aKeyValue.length > 1) {
Shopify.queryParams[decodeURIComponent(aKeyValue[0])] = decodeURIComponent(aKeyValue[1]);
}
}
}
var collFilters = jQuery('.coll-filter');
collFilters.change(function() {
var newTags = [];
var newURL = '';
collFilters.each(function() {
if (jQuery(this).val()) {
newTags.push(jQuery(this).val());
}
});
{% if collection.handle %}
newURL = '{{ collection.handle }}';
if (newTags.length) {
newURL += '/' + newTags.join('+');
}
var search = jQuery.param(Shopify.queryParams);
if (search.length) {
newURL += '?' + search;
}
location.href = newURL;
{% else %}
if (newTags.length) {
Shopify.queryParams.constraint = newTags.join('+');
}
else {
delete Shopify.queryParams.constraint;
}
location.search = jQuery.param(Shopify.queryParams);
{% endif %}
});
</script>
代码的作用是输出如下:http://domain.com/collections/all//collections/product
但我需要的是:http://domain.com/collections/product
问题应该在这部分(位置)。href = newURL;),但我不能使它正常工作。
我猜这将解决它:
newURL = '/{{ collection.handle }}';
这使得你的新url根相对;没有/你的url是相对于当前url的