如何使用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:
Option 1: Generate the Correct URL Directly in Handlebars (Recommended)
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:
- Wait for the DOM to be ready (or ensure your template has finished rendering) so you can access the link element.
- 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> - 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

