简体   繁体   中英

Cancelling the anchor when clicking on a div inside the anchor

I have an anchor element in my html:

<a class="info-tiles tiles-inverse has-footer" href="somepage.html?id=15">
  <div class="tiles-heading">
    <div class="pull-left">IT Department - Hosting environment</div>
  </div>
  <div class="tiles-body">
    <div class="nav-justified" style="font-size: small;">Started: 19-05-2015 07:00</div>
    <div class="btn btn-sm btn-default pull-right">AE</div>
    <div class="btn btn-sm btn-default pull-right">PJ</div>
    <div class="btn btn-sm btn-default pull-right">SL</div>
  </div>
  <div class="tiles-footer">
    <div class="progress">
      <div class="progress-bar progress-bar-info" style="width: 20%"></div>
    </div>
  </div>
</a>

This code renders like this:

示例渲染

The behavior is ok in general, that clicking on anywhere in this anchor should direct me to the another page, but I'd like to be able to click on those lightgrey tiles [SL][PL][AE] and display a context menu for those. What is a clean approach to change this behavior so that I still can click anywhere to navigate to the somepage.html, except if I click on those tiles, the navigation should not happen, and instead fire a javascript function (which would then display some context menu)?

If you use jQuery, you might want to take that approach:

$(".btn.btn-sm.pull-right").on("click", function(e) {
    e.stopPropagation();

    $(this).find(".context-menu").toggle();

    e.preventDefault();
    return false;
});

Then you'd need to write a

<div class="context-menu">
    <ul>
        <li>Element</li>
    </ul>
</div>

and style it with basic css.

Edit: To support older version of IE, you might also add that just after the e.stopPropagation();

event.cancelBubble = true;

You can use stopPropagation event method:

 $('selector').on('click', function(e)  {
      e.stopPropagation();
      e.preventDefault();
      // your actions 
 }); 

This allows you to stop bubbling from the button to outside, and prevent to execute the anchor event. I add preventDefault() to avoid default button actions

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