2016-11-14 13 views
0

私は幾分ばかげた問題に遭遇しました。次のHTMLを見てみましょう :Select兄弟が期待どおりに機能しない

<div id="product-container"> 
    <div id="product-1" class="product"> 
     <img id="product-img-1" class="product-images"> 
    </div> 

    <div id="product-2" class="product"> 
     <img id="product-img-2" class="product-images selected"> 
    </div> 

    <div id="product-3" class="product"> 
     <img id="product-img-3" class="product-images"> 
    </div> 
</div> 

私がやりたいことは、それが「選択」またはあなたが製品の画像をクリックすると、それはのクラスを変更する最初の製品の画像クラスを設定するたびにページがロードされますその画像を「選択済み」にして、この同じクラスを他のクラスから削除します。

私は、次の

$("img.product-images").on('click', function(){ 
    $(this).addClass('selected').siblings().removeClass('selected'); 
}); 

これは動作しますが、あなたは画像をクリックした場合にのみ、ページがロードされたときに、これが動作しないでこれをテストしています。この問題を解決するには

は私が書いた次

function updateActiveImg(product = firstProduct()){ // returns first available product (I've tested this and this works as desired) 
    // attempt 1, doesn't work: it does add the class to the correct image, but when I click another it just adds the class to that image whithout removing it from its siblings 
    $('#product-' + product).addClass('selected').siblings().removeClass('selected'); 
    // attempt 2, doesn't work: this will remove the class from all the cildren, including the one I want selected 
    $('#product-' + product).addClass('selected').parent().find('.product-images').removeClass('selected'); 
    // attempt 3, doesn't work: thought this was the final solution, but don't see why it wouldn't work 
    $('#product-' + product).addClass('selected').parent().find('.product-images').not('#product-' + product).removeClass('selected'); 
} 

誰もが、私はここに欠けているものを知っていますか?

+0

主な問題は、あなたの 'img'要素には兄弟がないことです。彼らは異なる親を持っているので、彼らは兄弟ではありません。 –

+0

"ページが読み込まれても動作しません" - "動作しません"について詳しく説明してください。 clickイベントは起動しますが、他の '.product-images'は見つかりませんか?クリックイベントは発生しませんか? –

+0

どのようにページ/要素を読み込むのですか?あなたはajaxを使っていますか? –

答えて

3

親兄弟を取得してから要素を取得する必要があります。最初に機能させるには、最初の要素のclickイベントをトリガーします。

$("img.product-images").on('click', function(){ 
    $(this).addClass('selected').parent().siblings().find('.product-images').removeClass('selected'); 
}).eq(0).click(); 
+0

私はこれをクリックするだけで動作させることができますが、ページが読み込まれても動作しなくなります。 –

+0

@NicoV:更新されたコードを確認してください –

+0

@pranac私はあなたの答えを誤って読んで、試してみました。ありがとう。 –

関連する問題