2012-03-16 12 views
0

私は単純なギャラリーを作ろうとしていて、私のjQuery構文の何が間違っているのか分かりません。jQueryの構文ヘルプ - フィルムストリップギャラリーコード

サムネイル(最初の3つのリストアイテムの1つ)をクリックすると、clone()の画像とキャプションが表示され、li.expand(フルサイズの画像)に貼り付けられます。

私のjQuery関数の最初の2行は動作していますが、最後の2行は何もしていないようです。 $(this)を使っていますか?

HTML

<ul class="gallery2"> 
     <li> 
      <img src="img/1.jpg" /> 
      <p>Caption 1</p> 
     </li> 
     <li> 
      <img src="img/2.jpg" /> 
      <p>Caption 2</p> 
     </li> 
     <li> 
      <img src="img/3.jpg" /> 
      <p>Caption 3</p> 
     </li> 

     <li class="expand"> 
      <!-- This space will be filled with whatever thumbnail is selected --> 
     </li> 
</ul> 

jQueryの

$(".gallery2 li").click(function() { 
    $(".gallery2 li").removeClass("selected"); 
    $(this).addClass("selected"); 
    $(".gallery2 li.expand").html().remove(); 
    $(this).html().clone().appendTo(".gallery2 li.expand"); 
}); 

答えて

2

html()文字列ではなく、jQueryオブジェクトを返します。おそらくchildren()を使用することを意味しますか?さらに、.children().remove()を使用するのではなく、empty()を使用できます。これらの変更によって:

$(".gallery2 li").click(function() { 
    $(".gallery2 li").removeClass("selected"); 
    $(this).addClass("selected"); 
    $(".gallery2 li.expand").empty(); 
    $(this).children().clone().appendTo(".gallery2 li.expand"); 
}); 

また兄弟要素を選択するsiblings()を使用して検討するかもしれない:

$(".gallery2 li").click(function() { 
    var me = $(this); 
    me.siblings().removeClass("selected"); 
    me.addClass('selected'); 
    me.siblings('.expand').empty().append(me.children().clone()); 
}); 

そして、我々はすべてのことトラブルに行くつもりなら、なぜそれがより一般的にしませんそれをプラグインに変えることで?

$.fn.gallerize = function() { 
    this.on('click', 'li', function() { 
     var me = $(this); 
     me.siblings().removeClass('selected'); 
     me.addClass('selected'); 
     me.siblings('.expand').empty().append(me.children().clone()); 
    }); 
}; 

そして、それはギャラリーを作るために、この簡単です:

$('.gallery2').gallerize(); 

on JSFiddleそれを試してみてください。

+0

素晴らしい。 html()が文字列を返したことを知りませんでした。ありがとう! –