2017-06-26 7 views
0

displayItem関数を使用して配列jsonから次の項目を表示しようとしていますが、ボタンをクリックすると、フォームは最初の値(arrayResponse [0])を再ロードします。代わりに次のアイテムを表示するために何をすべきですか?JQueryは配列の次の項目を表示します

$(document).ready(function() { 
    var firstElement; 
    var arrayResponse; 
    var index = 0; 

    var request = new XMLHttpRequest(); 

    // When the file has loaded, 
    request.onload = function() { 

    // parse the JSON text into an array of post objects. 
    arrayResponse = JSON.parse(request.responseText); 

    var firstelement = arrayResponse[0]; 

    $("#name").val(firstelement.name); 
    $("#author").val(firstelement.author); 
    $("#content").val(firstelement.content); 

    // Pass the posts array to the callback. 

    }; 
    request.open("GET", "http://127.0.0.1:8887/posts.json", true); 
    request.send(null); 


    $("#nextButton").bind("click", function() { 

    displayItem(arrayResponse[++index]) 

    }); 

    function displayItem(item) { 
    $("#name").val(item.name); 
    $("#author").val(item.author); 
    $("#content").val(item.content); 
    } 
}); 
+0

[フォームのHTMLに次の項目を表示する方法]の可能な重複(https://stackoverflow.com/questions/44761891/how-to -display-next-item-on-form-html) –

+0

あなたは同じ質問を2回尋ねました:https://stackoverflow.com/questions/44761891/how-to-display-next-item-on-form-html、私これは良い方法だとは思わないStackOverflow –

答えて

0

変更この:これに

$("#nextButton").bind("click", function(){ 
    displayItem(arrayResponse[++index]) 
}); 

$("#nextButton").bind("click", function(){ 
    displayItem(arrayResponse[index]); 
    index++; 
}); 
+0

あなたの答えをありがとう.. :)しかし、再び最初の値を再ロードする – IProgrammer

+0

たぶん、jQueryのajax関数を使うのはいいアイデアです[jQuery get](https://api.jquery.com/jquery.get/) –

1

私はthis jsfiddleを作成し、完璧に動作しているようです。このtest json

を使用してコードをチェックします。あなたのjsonに何らかのエラーがあるはずです。

HTML:

<input id="name" /><br> 
<input id="author" /><br> 
<input id="content" /><br> 
<button id="nextButton">Next</button> 

のJs:

$(document).ready(function() { 
    var firstElement; 
    var arrayResponse; 
    var index =0;   

var request = new XMLHttpRequest(); 

// When the file has loaded, 
request.onload = function() { 

    // parse the JSON text into an array of post objects. 
    arrayResponse = JSON.parse(request.responseText); 

    firstelement = arrayResponse[0]; 

    $("#name").val(firstelement.id); 
    $("#author").val(firstelement.name); 
    $("#content").val(firstelement.username); 


    // Pass the posts array to the callback. 

}; 
request.open("GET", "https://jsonplaceholder.typicode.com/users", true); 
request.send(null); 



$("#nextButton").bind("click", function(){ 

    displayItem(arrayResponse[++index]) 

});  

function displayItem(item) { 
     $("#name").val(item.id); 
     $("#author").val(item.name); 
     $("#content").val(item.username);   
} 
}); 
+0

こんにちは!私のlocalhost(http://127.0.0.1:8887/posts.json)とURLを置き換え、jsfiddle.net..soの私のjsonファイルでそれを働かせてください。しかし、クロムブラウザでは動作しません! – IProgrammer

関連する問題