-3

イベントが発生した時点で要素に存在するテキスト値に応じて、クリック時に特定の要素のテキストを変更する次のコードがあります。

http://jsfiddle.net/TNDhL/

$('#left').on('click', function (){
if ($("#textContainer:contains('something')").length) {
    $('#textContainer').text('third text replacement');
    $('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
    $('#textContainer').text('now the next item');
    $('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
    $('#textContainer').text('new text here');
    $('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
    $('#textContainer').text('something');
    $('.elsewhere').text('text here');
}
});

$('#right').on('click', function (){
if ($("#textContainer:contains('something')").length) {
    $('#textContainer').text('new text here');
    $('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
    $('#textContainer').text('now the next item');
    $('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
    $('#textContainer').text('third text replacement');
    $('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
    $('#textContainer').text('something');
    $('.elsewhere').text('text here');
}
});

動作するバージョンについては、上記のフィドルを参照してください。

これをさらに簡単に拡張できるようにするために、これをより管理しやすくする方法を見つけたいと思います。このケースを処理するためのより良い方法はありますか? これを関数に凝縮し、変数を使用して #textContainer の値を格納するのがより理想的です。助言がありますか?

4

1 に答える 1

1

シンプルなカウンターで進行状況を追跡できるクロージャーの完璧なケースのように思えます。次のようになります。

var myTextRotator = (function () {
    var myPhraseArray = ["first phrase", "second phrase"],
        counter = 0;
    return {
       clickLeft: function () {
           counter -= 1;
           return myPhraseArray[counter]; //return array item or do your processing here
       },
       clickRight: function () {
           counter += 1;
           return myPhraseArray[counter]; //return array item or do your processing here
       }
    };
}());

clickLeftandclickRightメソッドを jQuery に関連付けます.on()。カウンターが 0 を下回ったり、配列の長さを超えたりしないように、そこに条件を追加する必要がある場合があります。

これを次のように使用します。

$(".left").on("click", function () {
    myTextRotator.clickLeft();
});

$(".right").on("click", function () {
    myTextRotator.clickRight();
});
于 2013-09-16T16:28:07.137 に答える