画廊瓦特/ jQuery的,JSON和上/下一个按钮。如果JSON请求返回undefined,旁听席上休息

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

  •  11-09-2019
  •  | 
  •  

我是一个开始编码器,了解到CSS,HTML和jQuery在实习这个夏天。我的老板要我创建具有一个主图像画廊,然后两个按钮来显示一个或下一个项目。他要我用JSON,让他们可以轻松地添加和删除图像。我有这么写的,我开始变0,然后当我点击上一页/下一页它递减/递增变量,然后又回到了JSON来寻找相应的图片。唯一的问题是,如果我有四个画面,如果该值低于零或高于3,它打破。结果怎样才可以有jQuery的告诉我们,如果JSON查找返回不确定的,这样我可以把它无论是环或禁用按钮?我想,if语句将是理想的,但我把它留给你。

$(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);
                });
            });
        }); 
    }); 
有帮助吗?

解决方案

OK,我现在明白了这个问题,我认为。

我将概括图像交换代码到换出给定的索引的当前图像的功能。我称这种功能setImageWithIndex()。然后我们就可以用该指数在.click()代码什么处理简单。

这需要保存data到另一个全球性的,jsonData

我也将节省的(a)在JSON数据返回的图像的数量和(b)在两个全局变量的当前图像索引(最初零)。

下面的代码。我也删除了一些jQuery和标准的JavaScript在那里它并没有真正添加任何东西取代它。

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);
    });
}

其他提示

可以使用的typeof测试对于返回变量输入:

$.getJSON("layout.json",function(data){
    // check for undefined return value
    if (typeof data == 'undefined') {
        // handle your undefined cases
    }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top