以下代码向菜单添加和删除“事件”类 (.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
});
或者您真的需要跨度吗?为什么不直接添加/删除类
$("#menu a").click(function() {
$("#menu a.active").removeClass("active filet_menu");
$(this).addClass('filet_menu active');
});
关于javascript - 如何删除元素内的跨度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13766256/