简体   繁体   中英

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). 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. 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. 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.

This can be achieved via 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(...); } $("span .button").click(function (e) { // Keep the anchor tag from firing when the user clicks on return false; });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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