갤러리 w/jquery,json 및 이전/다음 버튼이 있습니다.는 경우 json 요청에 반환 정의되지 않은,갤러리 나누기
문제
저는 처음 coder,배 CSS,HTML,Jquery 에서 인턴십을 이번 여름에.보고 싶은 나를 만드는 갤러리가 있는 하나의 주요 이미지,그리고 그 다음에 두 개의 버튼이 표시는 다음 또는 이전 항목입니다.그는 저를 사용 json,그래서 그들은 쉽게 추가할 수 있습과 이미지를 제거합니다.나는 그것도록 작성되었을 시작으로 변 0,다음]을 클릭하면 이전/다음 그것을 감소/증가 변수이고,그가 다시 json 을 찾기 위해 해당하는 사진입니다.는 경우 내가 네 사진 경우,가치는 영하거나 위 3,됩니다.
어떻게 미래에 더 나은 작업을 수행합니다 jquery 으면 말 json 조회 반환되는 정의되지 않은,그래서 그것을 가질 수 있거나 반복 또는 비활성화 버튼?내 생각하는 경우 문 것 이상적인,하지만 난 그것을 둡니다.
$(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);
});
});
});
});
해결책
좋아,내가 이해하는 문제가 이제 나는 생각한다.
나는 것이 일반화 이미지-코드를 교환하는 기능으로 전환되는 현재 주어진 이미지는 인덱스입니다.내가 이 기능 setImageWithIndex()
.그런 다음 우리가 다룰 수 있으로 간단하게 무엇을 인덱스 .click()
코드입니다.
이 필요로 저장 data
으로 다른 글로벌 jsonData
.
또한 것에 저장(a)이미지의 수를 반환에 JSON 데이터 그리고(b)이 현재 이미지수(처음에는 제)에서 두 개의 전역 변수입니다.
코드는 다음과 같습니다.또한 일부를 제거 jquery 로 대체한 표준 자바 스크립트는지 정말로 아무것도 추가.
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
}
});