简体   繁体   English

使<a>标签中的 href 属性具有反应性</a>

[英]Make href attribute in <a> Tag reactive

I have the following HTML code:我有以下 HTML 代码:

<input id="number" type="number" value="1" min="1" max="10"> <a href="/products/add-to-cart/<%= products[i]["_id"] %>" class="btn btn-light">Add to cart</a>

This code displays an input number field and a button that links to a route for express.此代码显示一个输入数字字段和一个链接到快递路线的按钮。

My question is, how can I get the number entered in the input field as a parameter to the href attribute of the <a> tag?我的问题是,如何将输入字段中输入的数字作为<a>标签的href属性的参数?

I need to also send the quantity the user wants to add to the shopping cart, to my route so I can add that to the cart.我还需要将用户想要添加到购物车的数量发送到我的路线,以便我可以将其添加到购物车中。

Your help would be most appreciated.您的帮助将不胜感激。

Listen for the change event to be fired on the input:number node, then just reset the href attribute on the anchor node, as shown in the example below.监听在input:number节点上触发的 change 事件,然后只需重置锚节点上的href属性,如下例所示。 Could also just use a click event handler to window.location to the created URL or switch to a form也可以只使用click事件处理程序将window.location用于创建的 URL 或切换到form

 document.querySelector('#number').addEventListener('change', evt => { const value = evt.target.value; document.querySelector('a').href = `/products/add-to-card/${value}`; console.log(`HREF is now: ${document.querySelector('a').href}`); }, true);
 <input id="number" type="number" value="1" min="1" max="10"> <a href="/products/add-to-cart/1" class="btn btn-light">Add to cart</a>

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

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