0

ギャラリー用に自分のライトボックスに制限を設定することに問題があります

    <script>


var imagenumber = 0;

    function btnleft(){
        load = imagenumber-=1;
        document.getElementById('lightboxcontent').innerHTML=imagelist[load];

        }

function btnright(){
    load = imagenumber+=1;
    if (load==undefined){load=imagenumber-=1}
    document.getElementById('lightboxcontent').innerHTML=imagelist[load];
    }
</script>

次に、配列

var imagelist=new Array(); // regular array (add an optional integer
imagelist[0]="image1.jpg";       // argument to control array's size)
imagelist[1]="image2.jpg";
imagelist[2]="image3.jpg";

次のボタンを 3 回以上クリックすると、「未定義」というエラー メッセージが表示されます。アレイの制限を取得するにはどうすればよいですか?

4

2 に答える 2

1

で試してみてください

 function btnleft(){
    var load = imagelist[imagenumber-=1];
    if (load) // imagenumber in array boundaries
        document.getElementById('lightboxcontent').innerHTML = load;
    else
        imagenumber = 0;
 }
 function btnright(){
    var load = imagelist[imagenumber+=1];
    if (load) // imagenumber in array boundaries
        document.getElementById('lightboxcontent').innerHTML = load;
    else
        imagenumber = imagelist.length-1;
 }

しかし、ArrayJavascript の s にはサイズの制限はなく、(無限の) リストに似ています。それらの長さに制限を設定することはほとんどできません-特に、 number 引数が初期化の目的のためだけであるコンストラクターでは設定できません。

length配列のプロパティを使用して、インデックスが配列の境界内にあるかどうかを確認できます: i >= 0 && i < arr.length. 私のコードは、そのインデックスに項目があるかどうかを確認し (2 番目の関数も意図しているようです)、そうでない場合はインデックスをリセットします。

于 2012-05-16T18:45:33.780 に答える
0

「次のボタン」をクリックするとbtnright()関数が呼び出されると思います。

その場合は、 の間違った値をテストしていますundefined。関数を次のように書き換えることができます。

function btnright(){
  load = imagenumber += 1;
  // Test the value at the index of the array, not your index variable.
  if (imagelist[load] === undefined) {
    load = imagenumber-= 1;
  }
  document.getElementById('lightboxcontent').innerHTML = imagelist[load];
}

スタイル的には、これはまだ最高ではありません。load値は常に重複するため、変数は必要ありませんimagenumber。次のような関数をリファクタリングできます。

function btnright() {
  // If we have a new array value do something.
  if (imagelist[imagenumber + 1] !== undefined) {
    // Increment the index and load the new image.
    document.getElementById('lightboxcontent').innerHTML = imagelist[++imagenumber];
  }
}

function btnleft() {
  // If we're not on the first image do something.
  if (imagenumber !== 0) {
    // Decrement the index and load the new image.
    document.getElementById('lightboxcontent').innerHTML = imagelist[--imagenumber];
  }
}
于 2012-05-16T18:53:23.633 に答える