2011-07-25 15 views
2

私は、次のHTML持っている:私は次のことを持って選択したリンクについては削除選択したクラスのjqueryの

<a href="#">img/a.jpg</a> 
<a href="#">img/b.jpg</a> 
<a href="#">img/c.jpg</a> 

を:

$(function() { 
      $("a").click(function() 
      { 
      var current = $(this); 
      var name = current.attr('href'); 
      current.addClass("selected"); 
      var prev = current.closest("a").find("a.selected"); 
      prev.removeClass("selected"); 
       return false; 
      }); 
     }); 

問題は後に、私はいくつかのリンクに前のをクリックしてくださいということです私がクリックしたものは、選択解除されません(選択されたクラスを削除します)。どんな助けでも大歓迎です。

答えて

4

最初に選択したクラスを持つすべての要素を削除し、選択したクラスを現在のクラスに適用することができます。

あなたができる
$("a").click(function({ 
    var current = $(this); 
    var name = current.attr('href'); 

    //Remove all 
    $('.selected').removeClass('selected'); 

    //Add to current 
    current.addClass("selected"); 

    return false; 
}); 
4

$(function() { 
      $("a").click(function() 
      { 
      var current = $(this); 
      var name = current.attr('href'); 
      $('a.selected').removeClass('selected'); 
      current.addClass("selected"); 

       return false; 
      }); 
     }); 

あなたの例では動作しません。最も近いそれはDOMツリー

+0

( '.parent()'のように)だけでなく、それ自身で始まります。したがって、 "prev"要素は常に( '.find()'に到着するまでは) '.closest()'呼び出しで呼び出されます。 –

1

を上がるので、私は次のことを試してみた:

$(function() { 
    $("a").click(function() { 

     //GEt the current element 
     var current = $(this); 
     var name = current.attr("href"); 

     //Remove the class from the previous element 
     $('.selected').removeClass("selected"); 

     //Add the class to the current element 
     current.addClass("selected"); 

     //Let's get back to work! 
     return false; 

    }) 
} 
1

.closestのあなたの使用は間違っているとは思いません。 .closestがマッチのためにツリーの上を見ていることを忘れないでください。したがって、あなたの場合は、最初にそれ自体を見つけて、選択されたクラスが適用されたアンカーについて(内部で)探します。 (私が読んだとおり、あなたのコードは、選択したクラスを適用したり削除したりする必要があります。

代わりに.siblingsを試してみてください。

$('a').click(function(e){ 
    // store the current anchor 
    var $a = $(this); 

    // add the selected class to this element 
    $a.addClass('selected'); 

    // look around to links nearby, with the selected class, and remove that class 
    $a.siblings('a.selected').removeClass('selected'); 

    // prevent further action 
    e.preventDefault(); return false; 
}); 

は、私が過度に広範である汎用的な$('a.selected')または$('.selected')を使用してのように感じるし、あなたがしたくないページ上のリンクをつかむことがあります。それは、私が代わりにthe followingを示唆している、と述べました。私は間違っている可能性がありますが、これはあなたのページの現在のナビゲーション部分(少なくともこれらすべてのアンカーが入っている同じコンテナ内)にその情報を保持します。

関連する問題