简体   繁体   English

在锚标签内创建按钮

[英]Creating button inside an anchor tag

I am building a retail website. 我正在建立一个零售网站。 In my product list page, I'm listing each product as a block (3 blocks per row). 在我的产品列表页面中,我将每个产品作为一个块列出(每行3个块)。 Inside each block, I want to show details like name, price, sale price, etc. I also want an "Add to Cart" button inside each block where if the user clicks on it, I will use a JS function to add the product to the cart. 在每个区块内,我想显示详细信息,例如名称,价格,销售价格等。我还希望在每个区块内显示“添加到购物车”按钮,如果用户单击该按钮,我将使用JS函数添加产品到购物车。 I want the entire block to be clickable and take the user to the product detail page when clicked. 我希望整个块都可单击,并在单击时将用户带到产品详细信息页面。 I have an anchor tag around the entire block. 我在整个街区周围都有一个锚标签。

My problem is when a user clicks on the Add to Cart button, it adds the item to the cart via JS, but then the anchor tag fires and takes the user to the details page. 我的问题是,当用户单击“添加到购物车”按钮时,它通过JS将商品添加到购物车,但随后触发了定位标记并将用户带到详细信息页面。 What's the best way to handle this? 处理此问题的最佳方法是什么?

I can move the Add to Cart button out of the block but I'd rather not as there is a border around the block. 我可以将“添加到购物车”按钮移出模块,但我不希望这样做,因为模块周围有边框。

You want to prevent the click event from firing on the ancestor of your button, you might also say: stop it from propagation up the DOM tree. 您要阻止单击事件在按钮的祖先上触发,您可能还会说:阻止它沿DOM树传播。

This can be achieved via Event.prototype.stopPropagation : 这可以通过Event.prototype.stopPropagation实现:

Run the code snippet, then click the link / button. 运行代码段,然后单击链接/按钮。 Notice how clicking the button does not fire click events on the anchor. 请注意,单击按钮如何不会触发锚点上的单击事件。

 var anchor = document.querySelector('[data-anchor]'); var button = document.querySelector('[data-button]'); anchor.addEventListener('click', function(e) { console.log('anchor clicked'); }); button.addEventListener('click', function(e) { e.stopPropagation(); console.log('button clicked'); }); 
 <a href="#" data-anchor> <div>Parent content</div> <button type="button" data-button>Button</button> </a> 

Thanks to both users who commented. 感谢两位对此发表评论的用户。 Although the answer was slightly different for me, with their help, I got pointed in the right direction and was able to figure it out from there. 尽管答案对我来说略有不同,但在他们的帮助下,我指出了正确的方向,并能够从中找出答案。 Here is my solution: 这是我的解决方案:


Add to Cart 添加到购物车

// Adds an item to the shopping cart function addToCart(productId, price) { ... addProductToCart(...); //将商品添加到购物车功能addToCart(productId,price){... addProductToCart(...); } $("span .button").click(function (e) { // Keep the anchor tag from firing when the user clicks on return false; }); } $(“ span .button”)。click(function(e){//当用户单击return false时,不使锚标记触发;});

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

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