简体   繁体   中英

How do I make a span element inside an anchor tag as a non anchor element?

I have an anchor tag and a span and an i element embedded in the anchor tag-

<a href="home.html" class="list-group-item" data-toggle="collapse"
    aria-expanded="false" style="padding-left: 30px;" id="id1">
  <span
          id="id2" class="glyphicon glyphicon-eye-close"
          style="color: #d6d6d6 !important; font-size: 15px;" title="title1">
  </span> 
  <i class="glyphicon glyphicon-folder-close"></i>
  HOME 
</a>

When I click on the i element or the span element, the page redirects to home.html the way I want it to.

But I don't want to redirect the page to home.html when I click on the span element. I instead want to bind the span element with a different action for the click event. I know that a quick fix is to have the span outside the anchor tag but unfortunately, I'm constrained to do so as per my requirements. Is there any way around this?

Any help will be appreciated. Thanks in advance.

You can cancel the event of a child element to prevent it from bubbling up to the parent.

Simply return false from the click event.

<a href="home.html">
  <span onclick="return clickme();"> 
          CLICK ME
  </span> 
  <i class="glyphicon glyphicon-folder-close"></i>
  HOME 
</a>

jsfiddle: https://jsfiddle.net/ksLbrj8y/3/

Note that cancelling the event is subject to a debate all of its own; see this thread for various techniques.

How to stop event propagation with inline onclick attribute?

You'd need to use JavaScript for this. You can add a click event listener to the <span> tag. Then, in the event handler, call .preventDefault() on the click event and redirect the user. Something like this:

document.querySelector('id2').addEventListener("click", function (e) {
    e.preventDefault();
    window.location = "http://example.com";
});

Be aware that this kinda violates good semantics (ie your mileage may vary when dealing with SEO, screen readers, and other non-standard consumers of your site).

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