简体   繁体   English

使用Javascript刷新每次点击的锚标签

[英]Refresh Anchor Tag on Each Click with Javascript

I have an ecommerce site that, every time someone clicks on "Add to Pallet" (we call it a pallet instead of a cart) the page refreshes to the same page and positions itself to the div of that product (try it out here: http://www.boostliquidation.com/ ). 我有一个电子商务网站,每当有人单击“添加到托盘”(我们称其为托盘而不是购物车)时,页面都会刷新到同一页面并将其自身定位到该产品的div(在此处进行尝试: http://www.boostliquidation.com/ )。 This happens using this Javascript: 使用以下Javascript会发生这种情况:

 $('input.returnLink').each(function(){
     $(this).attr('value',window.location.href + $(this).attr('data-skuhash'));
     }); 

And this anchor tag which is placed in a hidden input tag before the "Add to Cart" button: 并将此锚定标签放置在“添加到购物车”按钮之前的隐藏输入标签中:

<input type="hidden" value="back" name="return_to" class='returnLink' data-skuhash='#{%     for variant in product.variants %}{{variant.sku}}{% endfor %}' /> 

(The code in the {% %} is a language called Liquid used with Shopify websites). ({%%}中的代码是Shopify网站使用的称为Liquid的语言)。

This works fine... but only on the first product. 效果很好...但仅适用于第一个产品。 It adds the SKU number preceded by a # in the address bar. 它将在地址栏中添加SKU编号,并在其前面加上#号。 If a user adds another product, it refreshes to the top of the page, because it amends the SKU number to the existing SKU number already showing in the address bar. 如果用户添加了另一个产品,它会刷新到页面顶部,因为它将SKU编号修改为地址栏中已经显示的现有SKU编号。

How can I get the products added after the first to replace the existing SKU with their own so they'll refresh back to the product and not back to the top of the page? 如何在首次使用现有SKU替换现有SKU之后添加产品,以使它们刷新回到产品而不是页面顶部?

I'd probably try to use the string.replace() 我可能会尝试使用string.replace()

var str = window.location.href;
var hash = $(this).attr('data-skuhash');

if (str.match('#\w\w+'){
   str.replace('#\w\w+', hash);
} else {
    str = str + hash;
}

Looks for any hashes on the end of the url, replaces if it finds one, adds one if it doesn't. 在网址末尾查找任何哈希,如果找到则替换该哈希,如果找不到则添加一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM