2

>> JSFIDDLE <<

var imgFilterBtn = $("nav > ul > li > ul > li > a");

$("img").fadeIn("slow");

imgFilterBtn.click(function() {
    var fadeInClass = $(this).attr("id");
    var wrongFilter = $(this).parent("li").parent("ul").children("li").children("a");

    wrongFilter.removeClass(); // un-style all links in one sub-list
    $(this).toggleClass("selected"); // style selected link


    var wrongFilterID = wrongFilter.attr("id");
    $("#imgWrap").removeClass(wrongFilterID); // remove all classes from imgWrap that are equal to an ID all LI-items in  the current list


    $("#imgWrap").toggleClass(fadeInClass); // toggle the class that is equal to the ID of the clicked a-element

    $("img").hide(); // hide all images

    var imgWrapClass = $("#imgWrap").attr("class");
    $("#imgWrap").children("img." + imgWrapClass).fadeIn("fast"); // fade in all elements that have the same class as imgWrap
});   

スクリプトの動作を説明するコメントを含めるように最善を尽くしました。

1. 機能するもの:

  • ドキュメントの読み込み時に画像がフェードインする
  • 「選択された」クラスが切り替えられます (ただし、戻るには切り替えられません!)
  • クラス#imgWrapはオンに切り替えられますが、元に戻りません
  • liリストアイテム(実際にはその親)がクリックされると、画像が非表示になり、表示されます

2.うまくいかないこと

  • li-item をクリックしても、他のクラスは削除されません。
  • 上記のこと

3. 何が起こるべきか ユーザーがリンクをクリックすると、そのリンクの ID が に割り当てられたクラスに渡され#imgWrapます。ただし、このクラスが割り当てられる前に、THE SAME LIST (別のリストではない) の他のリスト項目の ID と同じ他のすべてのクラスが削除されます。したがって、 と をクリックするblackfashion、 とが削除されているはずですbrown #imgWrapfashionbrownblack

関数が不足していると推測していeachますが、よくわかりません。

4

1 に答える 1

2

問題は、その特定のリストのすべてのwrongFilter要素が含まれており、最初に選択された要素の ID を常に選択することです awrongFilter.attr("id")

切り替えについて: 既に選択されている要素を選択する場合は、最初にselectedクラスを削除してから再度追加します。に追加されたクラスに似てい#imgWrapます。

選択を実際に選択された要素に制限し、クラスの追加/削除を修正します。

// ...
// Only get the currently selected element
var wrongFilter = $(this).closest('ul').find('a.selected');
var wrongFilterID = wrongFilter.attr("id"); // get its ID

// toggle `selected` for the previous selected element and the current one;
// will remove the class if the previous selected element is the same as the
// current one 
wrongFilter.add(this).toggleClass('selected');

// ...

// if the class already exists, the same menu entry was clicked and we have 
// to remove the class
$("#imgWrap").toggleClass(fadeInClass, wrongFilterID !== fadeInClass);

// ...

しかし、今ではそれが可能でwrongFilterIDありundefined、次の呼び出しでremoveClassすべてのクラス form が削除されます#imgWrap。したがって、テストを追加する必要があります。

if(wrongFilterID) {
    $("#imgWrap").removeClass(wrongFilterID); 
}

別の問題はimgWrapClass、スペースで区切られたクラスの文字列になる可能性があることです。たとえば"fashion black"

.children("img." + imgWrapClass)

結果として

.children("img.fashion black")

これはあなたが望むものではありません。

その文字列から適切なセレクターを作成する必要があります。

// "fashion black" becomes "fashion.black"
var imgWrapClass = $.trim($("#imgWrap").attr("class")).replace(/\s+/g, '.');

すべてが修正されたので、正しく動作しているようです:

デモ

于 2012-07-09T16:27:27.223 に答える