简体   繁体   中英

How to make li clickable without affecting inner anchor?

I have a list of products for which I am using below li:

When user clicks anywhere on the li I want use to send to product details page eg /product/id/. When user mouse over the li I also display an icon which when clicked allows users to add product in Favorites.

<ul>
        <li class="media">
            <div class="media-left">
                <a href="/product/123/">
                    <thumb>
                        <div class="thumb">
                            <img src="/images/company-logo.jpg">
                        </div>
                    </thumb>
                </a>
            </div>
            <div class="media-body">
                <div class="item-actions autohide pull-right">
                    <a title="Add to Favorites"><i class="material-icons">favorite</i></a>
                </div>
                <div class="media-heading b">
                    <a href="/product/123">Demo Product</a>
                </div>
                <div class="text-sm">
                    <div style="height:16px;overflow:hidden;">Demo Manufacturer</div>
                </div>
            </div>
        </li>
    </ul>

I know I can make the whole li clickable and send user to product details page using javascript.

<li (click)="sendToproductDetailsPage(123)">
.....
</li>

But the issue with this approach is that when I click on Favorite icon, it also send users to product details page.

Can anyone please guide how to achieve this with pure JavaScript?

You clearly have an event handler for the "Favorite" a link that handles adding the thing to the favorites. Have that event handler stop propagation. Since the click stops as of that a , it never bubbles up to the li , and you don't have to worry about it triggering the li 's click handler.

If you're hooking up events through addEventListener , your handler gets an event object that has stopPropgation , so:

yourEventArgument.stopPropagation();

If you're using onxyz -style event handlers, return false from the handler; it does the same thing stopPropgation does (more on my blog: The true story 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