You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript结合Handlebars修改锚点链接中的URL品牌部分

Hey Gavin, let's work through this problem together. You've got a size guide link with a unique ID, and you need to swap out the brand part of the URL using Handlebars' {{product.brand.domain}} value. Here are two reliable approaches:

Since you're already using Handlebars, the simplest and most efficient way is to build the URL directly in your template. This avoids needing extra JavaScript entirely—Handlebars will replace the variable during rendering.

Just update your anchor tag to include the Handlebars variable in the href:

<a href="https://example.com/sizeguide/{{product.brand.domain}}.html" id="size-guide" target="_blank">
  <span class="pull-right">View Size Guide</span>
</a>

When Handlebars renders the template, {{product.brand.domain}} will be replaced with the actual brand domain value (e.g., nike or adidas), giving you the correct URL right out of the box.

Option 2: Modify the Link with JavaScript Post-Rendering

If for some reason you can't update the template directly (maybe legacy code constraints), you can use JavaScript to tweak the URL after the page/rendering is complete. Here's how:

  1. Wait for the DOM to be ready (or ensure your template has finished rendering) so you can access the link element.
  2. Grab the brand domain value from Handlebars. You can either expose it to the global scope or store it in a hidden element in your template:
    <!-- Add this hidden element somewhere in your Handlebars template -->
    <span id="brand-domain" style="display: none;">{{product.brand.domain}}</span>
    
  3. Update the link's href using the unique ID you already set:
    // Wait for DOM content to load
    document.addEventListener('DOMContentLoaded', function() {
      // Get the link element
      const sizeGuideLink = document.getElementById('size-guide');
      // Get the brand domain from the hidden element
      const brandDomain = document.getElementById('brand-domain').textContent.trim();
      // Replace the "brand" part in the URL
      // Using a regex to safely replace the last segment before .html
      sizeGuideLink.href = sizeGuideLink.href.replace(/\/([^\/]+)\.html$/, `/${brandDomain}.html`);
    });
    

Why Option 1 is Better

Building the URL directly in Handlebars is cleaner, faster, and avoids any potential race conditions (like trying to modify the link before it exists in the DOM). Only use Option 2 if you have no other choice.

内容的提问来源于stack exchange,提问作者Gavin5511

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:16:11