3

私は、一度に1つのDIVを表示し、残り(私が取った例では2つ)を非表示にできるスクリプトを探しています。さらに、ユーザーに前後に移動してもらいたいです。

すなわち

ユーザーが次をクリックすると、DIV 1が表示され、DIV3まで続きます。ユーザーはDIV2からDIV1までトラバースできるはずです。

この開発は面白いと思いました

http://jsfiddle.net/meetrk85/Y7mfF/

事前に10億に感謝します.....

4

1 に答える 1

3

次のHTMLが与えられます:

<div class="sample">div1</div>
<div class="sample">div2</div>
<div class="sample">div3</div>
<a href="#" id="display" class="display">next</a>
<a href="#" id="display1" class="display">prev</a>

次のjQueryは要件を満たしているようです。

// selects all the divs of class='sample',hides them, finds the first, and shows it
$('div.sample').hide().first().show();

// binds a click event-handler to a elements whose class='display'
$('a.display').on('click', function(e) {
    // prevents the default action of the link
    e.preventDefault();

    // assigns the currently visible div.sample element to a variable
    var that = $('div.sample:visible'),
        // assigns the text of the clicked-link to a variable for comparison purposes
        t = $(this).text();

    // checks if it was the 'next' link, and ensures there's a div to show after the currently-shown one
    if (t == 'next' && that.next('div.sample').length > 0) {
        // hides all the div.sample elements
        $('div.sample').hide();

        // shows the 'next'
        that.next('div.sample').show()
    }
    // exactly the same as above, but checking that it's the 'prev' link
    // and that there's a div 'before' the currently-shown element.
    else if (t == 'prev' && that.prev('div.sample').length > 0) {
        $('div.sample').hide();
        that.hide().prev('div.sample').show()
    }
});​

JSフィドルデモ

参照:


補遺:

リンクされたデモでhtmlを変更した理由の簡単な説明:

<div name="sample">div1</div>
<div name="sample">div2</div>
<div name="sample">div3</div>
<a href="#" id="display" value="display">next</div>
<a href="#" id="display1" value="display">prev</div>
  • aのname属性はdiv目的を果たしません。確かに、すべての要素が同じ名前を共有している場合はそうではありません(input要素ではなく、によってリンクされているaため、名前を使用してくださいclass)。

  • value属性は要素との関連aがなく、私が知る限り、目的はありません。このため、上記のスクリプトでは、属性が使用されていても有効classであったとしても、属性の同じ「値」が共有されていたため、ここでも名前を使用することを選択しました。data-*

  • 終了</div>タグは何も閉じていなかったため、に変更されました</a>

于 2012-04-27T19:31:48.077 に答える