简体   繁体   中英

Button inside hyperlink div

I have an element with an hyperlink. Inside the are also buttons, which should trigger their button actions, without triggering the hyperlink.

Demo code:

<a href="element.html">
 <div class="element_card">
   This is an card for an element with an hyperlink over the card.
    <button type="button" onclick="like_element()">
      Like the element but do not trigger the hyperlink.
    </button>        
 </div>
</a>

How can I disable the hyperlink for the button or cancel the event, so that the button area ia only triggering the onclick function for the button but not the hyperlink.

您可以使用event.stopPropagation()来阻止点击在链上传播。

You can use event.stopPropagation() to prevent further propagation of the current event in the bubbling phases.

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

See if this works for you.

The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented) See if this works for you.

Answer

<a href="element.html">
 <div class="element_card">
   This is an card for an element with an hyperlink over the card.
    <button type="button" onclick=" return like_element()">
      Like the element but do not trigger the hyperlink.
    </button>        
 </div>
</a>

using this inside href javascript:void(0)

 function like_element(){ console.log('working....!') }
 .element_card{ background-color: green; }
 <a href="javascript:void(0)"> <div class="element_card"> This is an card for an element with an hyperlink over the card. <button type="button" onclick=" return like_element()"> Like the element but do not trigger the hyperlink. </button> </div> </a>

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