javascript - 如何删除元素内的跨度?

标签 javascript jquery css wrapper unwrap

以下代码向菜单添加和删除“事件”类 (.active) 它还向事件链接添加跨度类 <span class="filet_menu"></span> .

如何删除这个跨度类?我试过 unwrap 但它没有删除 span 类“unwrap”。

这是我的代码:

$("#menu a").click(function() {
  $("#menu a").each(function() {
    $(this).removeClass("active");

    //Don't work :
    //$(this).unwrap('<span class="filet_menu"></span>');
    //$(this).contents().unwrap();
    //$('(this) > .active').unwrap();
  });
  $(this).addClass("active");
  $(this).wrapInner('<span class="filet_menu"></span>');
});
.active {
  color: #32c0ce !important;
}

.filet_menu {
  border-bottom: 2px solid #32c0ce;
  padding-bottom: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <div id="header">
    <div id="contenu_header">
      <h1>Sébastien Gicquel</h1>
      <ul id="menu">
        <li><a id="bt_diaporama" href="#diaporama">Home</a></li>
        <li><a id="bt_presentation" href="#presentation">Présentation</a></li>
        <li><a id="bt_realisations" href="#realisations">Réalisations</a></li>
        <li><a id="bt_contact" href="#contact">Contact</a></li>
      </ul>
    </div>
    <!-- fin contenu_header -->
  </div>
  <!-- fin header -->
  <div id="page">

最佳答案

您需要先找到内容才能解包。而且你不需要每个循环

$("#menu a").click(function() {         
     $("#menu a.active").removeClass("active");
     $(this).addClass("active");
     $('span.filet_menu').contents().unwrap();// get previous span contents first and unwrap
     $(this).wrapInner('<span class="filet_menu"></span>');// this wraps current anchor's contents  
 });           

http://jsfiddle.net/syXnH/

或者您真的需要跨度吗?为什么不直接添加/删除类

$("#menu a").click(function() {
    $("#menu a.active").removeClass("active filet_menu");
    $(this).addClass('filet_menu active');
});​

http://jsfiddle.net/HwTNz/

关于javascript - 如何删除元素内的跨度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13766256/

相关文章:

javascript - 错误 "“Error: Unknown provider: bProvider <- b” 中的字母/字母代表什么?”

jquery - jQuery 中的 X-HTTP-Method-Override?

jquery - 3 个备用 li 的独立样式

javascript - 更改复选框检查的 <div> 背景

javascript - sencha touch 中的切换和动画

javascript - 在工具提示中将秒转换为时间

javascript - SAPUI5部署: minimal set of files required to run

javascript - 传单L.control.attribution

javascript - Jquery:windows.onunload 在 Firefox 和 Chrome 中不起作用

javascript - 页面加载时,@Url.Action 为 null 或 javascript 中的 ""