简体   繁体   中英

next and previous JSON data with javascript

I' would like to create Next/Previous buttons for json array, but I can't get it to work. This is the last one I have tried

 <div id="text"></div>
 <button name="prev">go to previous div</button>
<button name="next">go to next div</button>
 <script>

myFunction([
{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
]);


function myFunction(arr) {
    var out = "";
    var i ;
    out = '<p>' +  arr[i].text + '</p> <br>';
    document.getElementById("text").innerHTML = out;
}
</script>
<div id="text">
</div>
<script>
var i = 0;
let arr = [
{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
];
setInterval(function myFunction() {
    var out = "";
    out = '<p>' +  arr[i].text + '</p> <br>';
    document.getElementById("text").innerHTML = out;
  console.log(out);
  if (i < arr.length - 1) {
    i += 1;
  } else {
    i = 0;
  }
}, 1000)
</script>

You can convert json data to string or better say html with $.each like below. as you tagged jQuery , here is jQuery approach:

 myFunction([{ "text": "text0" }, { "text": "text1" }, { "text": "text2" }, { "text": "text3" } ]); function myFunction(arr) { $.each(arr, function(i, v) { $('#text').append('<div>' + v.text + '</div>'); }); } var divs = $('.mydivs>div'); var now = 0; divs.hide().first().show(); $("button[name=next]").click(function(e) { divs.eq(now).hide(); now = (now + 1 < divs.length) ? now + 1 : 0; divs.eq(now).show(); }); $("button[name=prev]").click(function(e) { divs.eq(now).hide(); now = (now > 0) ? now - 1 : divs.length - 1; divs.eq(now).show(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="text" class="mydivs"></div> <button name="prev">go to previous div</button> <button name="next">go to next div</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM