Galeria w jquery /, json, e prev / próximos botões. Se o pedido json retorna indefinido, a galeria breaks

StackOverflow https://stackoverflow.com/questions/1658262

  •  11-09-2019
  •  | 
  •  

Pergunta

Eu sou um programador de início, CSS aprendeu, HTML e jQuery em um estágio neste verão. Meu chefe me quer criar uma galeria que tem uma imagem principal, e, em seguida, dois botões para exibir o item seguinte ou anterior. Ele quer que eu use JSON, de modo que eles podem facilmente adicionar e imagens remover. Eu tê-lo escrito para que, eu começo com uma variável 0, então quando eu clico anterior / seguinte ele diminui / incrementos da variável, e depois volta para o JSON para olhar para a imagem correspondente. O único problema é que se eu tiver quatro fotos, se o valor estiver abaixo de zero ou acima de 3, ele quebra.
Como posso ter o tell jquery se a pesquisa json voltou indefinido, para que eu possa tê-lo tanto loop ou desativar o botão? Suponho que uma instrução if seria o ideal, mas deixo isso para você.

$(document).ready(function(){
    $.getJSON("layout.json",function(data){

    // Then put the first picture up from the json data...
        $("<img />").attr({
            id: "0-middle_image", 
            class: "middle_image", 
            src: data.items[0].image ,
            })
        .appendTo("div#middle_image");

    // because I'm starting with the zeroth object, middleimage variable is 0
        var mi_val = 0 

    // when you click one of the cycle buttons...
        $("div.cycle_button").click(function(){
        //if it is the previous, decrement mi_val, else, increment mi_val
            if ( $(this).attr("id") == "button_prev") 
                         {--mi_val;}
            else {++mi_val;}
        //then, call the appropriate image object from the json
            $("img.middle_image").fadeOut(500,function(){
                $(this).attr({src: data.items[mi_val].image})
                .fadeIn(500);
                });
            });
        }); 
    }); 
Foi útil?

Solução

OK, eu entendo o problema agora eu acho.

Eu generalizar o código de troca de imagem em uma função que swaps fora a imagem atual dado um índice. Eu chamei esta função setImageWithIndex(). Então, podemos lidar apenas com o que o índice está no código .click().

Isto requer salvar o data em outro global, jsonData.

Gostaria também save (a) o número de imagens devolvidos nos dados JSON e (b) o índice de imagem atual (inicialmente zero) em duas variáveis ??globais.

Aqui está o código. Eu também removeu algumas jquery e substituiu-o com javascript padrão onde ele realmente não acrescenta nada.

var imageCount;
var currentImage = 0;
var jsonData;

function setImageWithIndex(index) {
    $("img.middle_image").fadeOut(500, function() {
         $("img.middle_image")
            .attr({src: jsonData.items[index].image})
            .fadeIn(500);
    });
}

window.onload = function() {
    $.getJSON("layout.json", function(data) {
        jsonData = data;

        $("<img />").attr({
            id: "0-middle_image", 
            class: "middle_image", 
            src: data.items[0].image
        })
        .appendTo("div#middle_image");

        /* <PSEUDOCODE class="may not work"> */
        imageCount = data.items[0].length;
        // ie: save the number of images in a global variable
        /* </PSEUDOCODE> */
    }

    $("div.cycle_button").click(function() {
        if (this.id == "button_prev")
            if (currentImage > 0)
                setImageWithIndex(--currentImage);
        else
            if (currentImage < imageCount)
                setImageWithIndex(++currentImage);
    });
}

Outras dicas

Você pode usar typeof para testar o tipo de variáveis ??de retorno:

$.getJSON("layout.json",function(data){
    // check for undefined return value
    if (typeof data == 'undefined') {
        // handle your undefined cases
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top