简体   繁体   English

如何将定位标记内的span元素设为非定位元素?

[英]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- 我有一个锚标记,一个span和一个嵌入在锚标记中的i元素-

<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. 当我单击i元素或span元素时,页面将按我希望的方式重定向到home.html。

But I don't want to redirect the page to home.html when I click on the span element. 但是,当我单击span元素时,我不想将页面重定向到home.html。 I instead want to bind the span element with a different action for the click event. 相反,我想为click事件使用不同的动作绑定span元素。 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. 只需从click事件中返回false。

<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/ 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? 如何使用内联onclick属性停止事件传播?

You'd need to use JavaScript for this. 您需要为此使用JavaScript。 You can add a click event listener to the <span> tag. 您可以将click事件侦听器添加到<span>标记。 Then, in the event handler, call .preventDefault() on the click event and redirect the user. 然后,在事件处理程序中,在click事件上调用.preventDefault()并重定向用户。 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). 请注意,这有点违反良好的语义(即,与SEO,屏幕阅读器和网站的其他非标准消费者打交道时,您的工作量可能会有所不同)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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