2016-08-01 4 views
0

В настоящее время я работаю над небольшим интерактивным использованием HTML, CSS и jQuery - ничего особенного.jQuery следующие и предыдущие данные JSON

У меня есть функция, которая успешно получает данные вопроса из json-файла, но при нажатии следующей или предыдущей функции кнопки, похоже, не срабатывают и не получают следующие данные вопросов из массива.

Любая помощь по этому вопросу будет оценена по достоинству.

Спасибо.

HTML

<div class="two"> 
    <h2>Question 1</h2> 
    <h3></h3> 
    <ul class="anwsers"> 
    </ul> 
    <ul class="controls"> 
    <li class="back"> 
     <button>Back</button> 
    </li> 
    <li class="next"> 
     <button>Next</button> 
    </li> 
    </ul> 
</div> 

JS

function questions(){ 
    var data = []; 
    var index = 1; 

    function question() { 
    $(".two h3").html(data[index].question); 
    } 

    $.ajax({ 
    url: '../json/data.json', 
    type: 'get', 
    dataType: 'json', 
    success: function(json) { 
     data = json; 
     question(); 
    } 
    }); 

    $('.two li.next button').on('click', function(index){ 
    console.log(index); 
    if (index < data.length - 1) { 
     index += 1; 
     question(); 
    } 
    }); 
    $('.two li.back button').on('click', function(index){ 
    console.log('Prev'); 
    if (index > 0) { 
     index -= 1; 
     question(); 
    } 
    }); 

} 

JSON

{ 
    "1": { 
    "question": "Which one of the five is least like the other four?", 
    "values": ["Snake", "Rat", "Lion", "Pig", "Cow", "Goat"], 
    "answer": "Snake" 
    }, 
    "2": { 
    "question": "Which number should come next in the series?<br/>1 - 1 - 2 - 3 - 5 - 8 - 13", 
    "values": ["8", "13", "21", "26", "31"], 
    "answer": "21" 
    }, 
    "3": { 
    "question": "Which one of the five choices makes the best comparison?<br/>PEACH is to HCAEP as 46251 is to", 
    "values": ["25641", "26451", "12654", "51462", "15264"], 
    "answer": "15264" 
    } 
} 
+0

откуда вы указали значение индекса в функции обратного вызова событий? – madalinivascu

+0

Вы вызываете question(); в вас события, но из каких данных? – madalinivascu

+1

Человек, которого вы кодируете, не имеет никакого смысла, где ваш html? – madalinivascu

ответ

0

объявить var data = []; из questions() функция. Сделать это глобальное

0

Rewrite это так:

var data = []; var index = 0; 

function question() { 
    if(data[index] != undefined) 
    {   
     $(".two h3").html(data[index].question); 
    } 
} 

function questions() { 
    $.ajax({ 
     url: '../json/data.json', 
     type: 'get', 
     dataType: 'json', 
     success: function(json) { 
      data = json; 
      question(); 
     } 
    });  
} 

$('.two li.next button').on('click', function() { 
    console.log(index); 
    if (index < data.length - 1) { 
     index += 1; 
     // enabling the buttons would be useful here 
     question(); 
    } else { 
     alert("No more questions"); 
    } 
}); 

$('.two li.back button').on('click', function() { 
    console.log('Prev'); 
    if (index > 0) { 
     index -= 1; 
     question(); 
    } else { 
     alert("This is the first one."); 
    } 
}); 
+0

Я пробовал это, но все, что я получаю, это сообщения журнала консоли. 'Live reload enabled. app.js: 36 r.Event {originalEvent: MouseEvent, type: "click", target: button, currentTarget: button, relatedTarget: null ...} app.js: 36 r.Event {originalEvent: MouseEvent, type: " нажмите ", цель: кнопка, currentTarget: button, relatedTarget: null ...} 3app.js: 45 Prev' –

+0

О, вы не можете использовать индекс в качестве своей целевой цели. Удалите их из скобок. Я сейчас обновляюсь. –

+0

Обновлен мой код. –

0

Удалить параметр индекса из мыши даже функции, потому что первый параметр в обработчик события щелчка содержат даже данные.

Поскольку "индекс" непосредственно accible в рамках этой функции:

$('.two li.next button').on('click', function(){ 
    console.log(index); 
    }); 
    $('.two li.back button').on('click', function(){ 
console.log(index); 
    }); 
0

Попробуйте следующий код

$.ajax({ 
    url: '../json/data.json', 
    type: 'get', 
    dataType: 'json', 
    success: function(json) { 
     data = json; 
     $.each(data,function(i,v){ 
      var answ = ''; 
      $.each(v.values,function(x,t){ answ +='<li>'+t+'</li>'; }); 
     $('body').append(' 
<div class="two" style="display:none;"><h2>Question '+i+'</h2><h3 style="display:none;">'+v.question+'</h3><ul class="anwsers">'+answ+'</ul> 
    <ul class="controls"> 
    <li class="back"> 
     <button>Back</button> 
    </li> 
    <li class="next"> 
     <button>Next</button> 
    </li> 
    </ul> 
</div>'); 
     }); 
     $('.two:first').show(); 
    } 
    }); 

    $('body').on('click','.two li.next button', function(index){ 
    $(this).closest('.two').hide(); 
    if($(this).closest('.two').is('.two:last')) { 
    $('.two:first').show(); 
    } else { 
    $(this).closest('.two').next().show(); 
    } 
    }); 
    $('body').on('click','.two li.back button', function(index){ 
    $(this).closest('.two').hide(); 
    if($(this).closest('.two').is('.two:first')) { 
    $('.two:last').show(); 
    } else { 
    $(this).closest('.two').prev().show(); 
    } 
    }); 

Демо: https://jsfiddle.net/9crboc3b/

-1
$('.two li.next button').on('click', function(index){ 
    console.log(index); //index is a event not the index you defined 
    if (index < data.length - 1) { 
     index += 1; 
     question(); 
    } 
}); 

вы можете изменить функцию (индекс) к функции (событию), которая прекрасна

Смежные вопросы