我需要将对象追加到两个不同的div
中,因此我使用对象数组,每次单击next按钮显示下一个对象。问题在于下一个按钮没有作用或没有采取任何措施。
var myArr = [
{id: 0 , question1 : "Question1 Question1 Question1.", question2: "Question2 Question2 Question2"},
{id: 1 , question1 : "Question1 Question1 Question1.", question2: "Question2 Question2 Question2"},
{id: 2 , question1 : "Question1 Question1 Question1", question2: "Question2 Question2 Question2."}
];
var i = 0;
display(0);
$('#prev__btn').click(function(){
for (var i = 0; i < myArr.length; i--){
if( i == myArr.length){
i--;
display(i);
}
}
});
$('#nxt__btn').click(function(){
for (var i = 0; i < myArr.length; i++){
if( i == myArr.length){
i++;
display(i);
}
}
});
function display(i) {
$('#question1').empty();
$('#question1').append(myArr[i].question1);
$('#question2').empty();
$('#question2').append(myArr[i].question2);
if(i == 0)
$('#prev__btn').hide();
else
$('#prev__btn').show();
if(i == myArr.length-1)
$('#nxt__btn').hide();
else
$('#nxt__btn').show();
}
答案 0 :(得分:1)
尝试
var myArr = [
{id: 0 , question1 : "Question1-0 Question1-0 Question1-0.", question2: "Question2-0 Question2-0 Question2-0"},
{id: 1 , question1 : "Question1-1 Question1-1 Question1-1.", question2: "Question2-1 Question2-1 Question2-1"},
{id: 2 , question1 : "Question1-2 Question1-2 Question1-2", question2: "Question2-2 Question2-2 Question2-2."}
];
let move= n=> box.innerHTML = inj(item.innerHTML, myArr[(idx+=n+k)%k]);
let inj= (s,o)=> s.replace(/\${(.*?)}/g,(x,g)=>o[g]);
let idx= 0, k=myArr.length;
<button onclick="move(-1)">Prev</button>
<button onclick="move(1)">Next</button>
<div id="box"></div>
<template id="item">
<div>id: ${id}</div>
<div>q1: ${question1}</div>
<div>q2: ${question2}</div>
</template>