2

クラス「右矢印」または「左矢印」の div をクリックしたときに、オブジェクトにクラスを追加したいと考えています。http://jsfiddle.net/では完璧に動作しますかしかし、私のサイトでは機能しません:(

誰でも私を助けることができますか?

jQuery:

var currentPage = 0;
var lastPage = ($(".post-preview > div").length)-1;
currentPage = $('.post-preview > div.show').attr('id');

$('.news > .right').stop().click(function() {
    if (currentPage == lastPage) {
            $('.post-preview > div#' + lastPage).hide();
            $('.post-preview > div#' + lastPage).removeClass('show');

        $('.post-preview > div#0').fadeIn(300);
        $('.post-preview > div#0').addClass('show');
        currentPage = 0;
    } else {
        $('.post-preview > div#'+currentPage).hide();
        $('.post-preview > div#'+currentPage).removeClass('show');
        currentPage++;
        var nextPage = currentPage;
        currentPage--;
        $('.post-preview > div#'+nextPage).fadeIn(300);
        $('.post-preview > div#'+nextPage).addClass('show');
        currentPage = nextPage;
    }
 });

 $('.news > .left').stop().click(function() {
     if (currentPage == 0) {
        $('.post-preview > div#0').hide();
        $('.post-preview > div#0').removeClass('show');

        $('.post-preview > div#' + lastPage).fadeIn(300);
        $('.post-preview > div#' + lastPage).addClass('show');
        currentPage = lastPage;
    } else {
        $('.post-preview > div#'+currentPage).hide();
        $('.rpost-preview > div#'+currentPage).removeClass('show');
        currentPage--;
        var nextPage = currentPage;
        currentPage++;
        $('.post-preview > div#'+nextPage).fadeIn(300);
        $('.post-preview > div#'+nextPage).addClass('show');
        currentPage = nextPage;
    }
});

show クラスの CSS:

.news > .post-preview > div.show    { display: inline-block !important; }

私のHTMLコード:

<div class="news">
<div class="arrow left"></div>
    <div class="post-preview">
        <div id="0" class='show'></div>
        <div id="1"></div>
        <div id="2"></div>

    </div>
<div class="arrow right"></div>
</div>
4

1 に答える 1

5

実行時におそらく存在しない要素にアクセスしようとしています。これが機能しない理由です。

$(function() { /* put code here */ } );コードをブロック内にラップする必要があります。

jsfiddleで機能する理由は、サイトが便宜上それを行うためです。

**編集**

JavaScript では、コードを独自のコンテキスト内に囲むことは (最善ではないにしても) 良い方法です。jQuery、jQuery UI、および多くの JavaScript ウィジェットとライブラリーをご覧ください。例えば ​​:

(function($) {    // receive $ as parameter; a jQuery instance

    /* place code here

})(jQuery);   // invoke the function above with this instance of jQuery

この理由は

  1. 別のバージョンの jQuery を使用する必要がある場合、または$変数をオーバーライドするライブラリを使用している場合、上記の関数は変更の影響を受けません。
  2. 宣言されたすべての変数 (つまりvar x = "foo";) は関数の外部では使用できないため、ウィンドウ (グローバル) の名前空間を汚染しておらず、必要なときに適切な値を取得できます。(関数の外部にアクセスする必要がある場合は、グローバル オブジェクトを公開します (例: window.someVar = localVar;)

ただし、上記の関数はブラウザによってロードされると実行され、DOM 要素が DOM ツリーに挿入される前に実行される可能性があります。これは、イベント リスナーなどを設定するスクリプトで問題になる可能性があります。したがって、DOM 要素が完全にロードされて使用できる状態になったときにのみ関数を実行する必要がある場合は、コードを jQuery onload コールバック内に囲みます。

jQuery(function() {

    /* place code here */

});

あるいは

(function($) {
    // executed right now

    $(function() {
        // executed only when the DOM is ready

        /* place code here */

    });

})(jQuery);

**更新**

あなたのコードをもう少し読んだ後、私は(コメントされているように)いくつかの奇妙なことしか見ることができません.

  1. ID は数値です。HTML仕様から

    ID および NAME トークンは文字 ([A-Za-z]) で始まり、その後に任意の数の文字、数字 ([0-9])、ハイフン ("-")、アンダースコア ("_") が続く場合があります、コロン (":")、およびピリオド (".")。

    したがって、IDプレフィックスを付ける必要があります...または要素インデックスに基づいて選択します

  2. クエリを常に再解析する代わりに、クエリを連鎖させることができます。

例えば

jQuery(function() {

var firstPage = $(".post-preview > div:first").index(); // index of the first page
var lastPage = $(".post-preview > div:last").index(); // index of the last page
var currentPage = $('.post-preview > div.show').index() || firstPage;  // default to 0

$('.news > .right').stop().click(function() {
    if (currentPage == lastPage) {
        currentPage = $('.post-preview > div:eq(' + lastPage + ')')
           .hide()
           .removeClass('show')
           .siblings('div:first')  // first DIV
           .fadeIn(300)
           .addClass('show')
           .index();  // should be 0... but we never know
    } else {
        // note : will receive the next element index
        currentPage = $('.post-preview > div:eq(' + currentPage + ')')
           .hide()
           .removeClass('show')
           .next('div')             // get next DIV element
           .fadeIn(300)
           .addClass('show')
           .index();
    }
 });

 $('.news > .left').stop().click(function() {
     if (currentPage == firstPage) {
        currentPage = $('.post-preview > div:eq(' + currentPage + ')')
           .hide()
           .removeClass('show')
           .siblings('div:last')  // last DIV
           .fadeIn(300)
           .addClass('show')
           .index();
    } else {
        currentPage = $('.post-preview > div:eq(' + currentPage + ')')
           .hide()
           .removeClass('show')
           .prev('div')
           .fadeIn(300)
           .addClass('show')
           .index();
    }
});

});

そしてあなたのHTML(IDはもう必要ありません)

<div class="news">
<div class="arrow left"></div>
    <div class="post-preview">
        <div class='show'>Preview 1</div>
        <div>Preview 2</div>
        <div>Preview 3</div>
    </div>
</div>
</div>
于 2013-02-05T14:19:45.550 に答える