3

次のコードは、メニューに「アクティブ」クラスを追加および削除します(.active)。また、アクティブリンクにスパンクラスを追加します<span class="filet_menu"></span>

このスパンクラスを削除するにはどうすればよいですか?unwrapを試しましたが、スパンクラス「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">

4

4 に答える 4

3

開封するには、まず中身にアクセスする必要があります。そして、各ループは必要ありません

$("#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/

于 2012-12-07T16:00:34.933 に答える
2

スパンを削除したいが、スパン内のデータを保持したいので、 .remove() は機能しません。これを使用できます:

$(this).html(
    $(this).find("span.filet_menu").html()
);
于 2012-12-07T15:48:34.513 に答える
1

コードを改善するためのいくつかの提案:

  • を追加および削除するのではなく、<span>ロード時にアイテムごとに1回作成します。DOMを変更するたびに、ブラウザは高価なレイアウト計算を実行する必要があります。active親クラスに応じて、CSSを介して表示を制御できます。
  • activeクラスを削除するためにすべてのメニュー項目を繰り返す必要はありません。セレクターを使用するだけです。

JavaScript:

$("#menu a").each(function() {
    $(this).wrapInner('<span class="filet_menu"></span>');
    $(this).click(function() {
        $('#menu a.active').removeClass('active');
        $(this).addClass('active');
    });
});

CSS:

.active
{
    color:#32c0ce !important;
}

.active .filet_menu
{
    border-bottom: 2px solid #32c0ce;
    padding-bottom:2px;
}
于 2012-12-07T16:06:19.203 に答える
1
$(".filet_menu", this).each(function () {
   $(this).replaceWith(this.childNodes);
});

http://jsfiddle.net/LMm28/

一方、スパンをずっとそこに置いて、.filet_menuクラスを追加/削除する方が簡単な場合があります。

于 2012-12-07T16:07:26.917 に答える