2017-11-06 6 views
0

"Generate quotote"ボタンをクリックすると現在の見積もりが削除されます。著者はJSONファイル上にある新しい引用文と著者に置き換えます。 JSONファイルが配列にあります。私はボタンをクリックするたびに次の見積もりが表示されるようにしたい。理想的には、JSON配列内で使用可能な引用符をランダム化して提供したいと思います。ボタンをクリックしてJavaScriptを使用してJSONファイル配列にあるデータで置き換えると、htmlデータやテキストを削除する方法

現在、ボタンをクリックすると最後の見積もりが表示され、+1のクリックごとに同じ見積もりが表示されます。これは、配列が最後のアイテムをピックアップして再度見積もりを出力するためです。 一時的ですが、もっと良い回避策があると思います。複数のJSONファイルをアップロードし、URL内のページ数を '..quotes - ' + pagecount + '.sjon'から変更してすべての引用符を取得します。

HTML: 
<!DOCTYPE html> 
<html> 
<head> 
    <!--Javascript for quote generator--> 
    <link rel="stylesheet" type="text/css" href="css/quoteStyles.css"> 
    </head> 
    <body> 
    <div id="quoteBox" class="quote-text"> 
    <span id="text"></span> 
     <p id="quotePara"> 


    </p> 
    <span id="text2"></span> 
    </div> 
    <div class="quote-author"> 
    - <span id="author"></span> 
    </div> 
     <div class="button-links"> 

     <button id="getQuote"class="btn btn-primary">Get Quote</button> 
     </div> 
</body> 
<script src="test.js"></script> 
<script src="http://rogerperez.us/quotes.json"></script> 

Javascriptを

JavaScript: 
var pageCount = 1; 
var i=0; 
var quotePara = document.getElementById("quotePara"); 
var getQuote = document.getElementById("getQuote"); 

// Request to get json data where the quotes are located 
getQuote.addEventListener("click", function() { 
    var ourRequest= new XMLHttpRequest(); 
    ourRequest.open('GET','http://rogerperez.us/quotes-1.json'); 
    ourRequest.onload= function() { 
    if (ourRequest.status>= 200 && ourRequest.status<400){ 
    var ourData= JSON.parse(ourRequest.responseText); 
    renderHTML(ourData); 
    } else{ 
    console.log("Connection Error, Please try again.") 
    } 
    }; 

    ourRequest.send(); 
    pageCount++; 

    if (pageCount>6){ 
    getQuote.classList.add('hide-me'); 
    } 
}); 

console.log(i); 

function renderHTML(data){ 
    var htmlString=""; 
    var htmlAuthor=""; 

    // for (j=0;j<data.length;j++){ 
    // remove 
    // } 
    for (i=0;i<data.length; i++){ 
    console.log("first",i); 
    htmlString=data[i].quote; 
    htmlAuthor=data[i].author; 
    console.log(i); 
    } 
    quotePara.insertAdjacentHTML('beforeend', htmlString); 
    author.insertAdjacentHTML('beforeend', htmlAuthor); 

} 

JSON

[ 
{"quote": "Success is not final; failure is not fatal: It is the courage to 
continue that counts.", 
    "author": "Winston S. Churchill"}, 
    {"quote":"Don't be afraid to give up the good to go for the great.", 
"author":"John D. Rockefeller"}, 
{"quote":"I find that the harder I work, the more luck I seem to have.", 
"author":"Thomas Jefferson"}, 
{"quote":"Try not to become a man of success. Rather become a man of value.", 
"author":"Albert Einstein"}, 
{"quote":"o one thing every day that scares you.", 
"author":"Anonymous"}, 
{"quote":"If you really look closely, most overnight successes took a long 
time.", 
"author":"Steve Jobs"}, 
    {"quote":"The real test is not whether you avoid this failure, because you won't. It's whether you let it harden or shame you into inaction, or whether you learn from it; whether you choose to persevere.", 
"author":"Barack Obama"}, 
    {"quote":"The successful warrior is the average man, with laser-like focus.", 
"author":"Bruce Lee"}, 
    {"quote":"If you really want to do something, you'll find a way. If you don't, you'll find an excuse.", 
"author":"Jim Rohn"}, 
    {"quote":"Be the type of person that when your feet hit the floor in the 
morning the devil says,aww shit.. they are up", 
    "author":"Dwayne (The Rock) Johnson"}, 
    {"quote":"Many of life's failures are people who did not realize how close 
they were to success when they gave up", 
    "author":"Thomas Edison"}, 
    {"quote":"Opportunities don't happen. You create them", 
    "author":"Chris Grosser"}, 
    {"quote":"I would rather risk wearing out than rusting out.", 
    "author":"Theodore Roosevelt"}, 
    {"quote":"When you play, play hard; when you work, don't play at all.", 
    "author":"Theodore Roosevelt"} 
    ] 

答えて

0

あなたの悩みはあなたの変数の値を置き換え、全体のデータ配列を反復処理し、その後のみの値を保持しているということです最後のデータ値:

// your code 
    for (i=0;i<data.length; i++){ 
    console.log("first",i); 
    htmlString=data[i].quote; 
    htmlAuthor=data[i].author; 
    console.log(i); 
    } 
    quotePara.insertAdjacentHTML('beforeend', htmlString); 
    author.insertAdjacentHTML('beforeend', htmlAuthor); 
あなたは、例えば、PAGECOUNT配列インデックスの引用ショーを作りたいと思った場合は

、あなただけだろう。目的はここにあるもの

// I recommend textContent instead 
    quotePara.textContent = data[pageCount].quote; 
    author.textContent = data[pageCount].author; 
+1

私は試しにそれ今夜を与え、あなたに戻って取得します場合は、単にあなたが機能renderHTMLを呼び出すことができます。お手伝いをしていただきありがとうございます。 – GauchoRoger

+1

それはうまくいった。ページ数を減らして0から開始し、固定数ではなくdata.lengthを使用できるようにしました。 – GauchoRoger

+0

よろしくお願いします!ハッピーコーディング。 –

0

完全にわかりません。しかし、ここに私の5セント価値があります。

  1. jsonをコードに追加することができます。これがあなたの例に従ってプリセットされていれば、HTMLでロードするだけです。それをサーバー側に追加するほうがずっと簡単です。それをajaxリクエストにするには、ボタンをクリックしたときにコードの最初に一度だけ実行したい場合は、変数にキャッシュしてから、次のボタンをクリックしてから、ajaxリクエストをチェックしてください。 。
  2. あなたの現在の見積もりインデックスであるバリューは、ボタン上で増分する必要があります。クリックしてください。これはランダムです。コメントと私は調整します。
  3. レンダリングを簡略化しました。あなたには、いくつかの派手なレンダリングをしたい場合、あなたは彼らが要求されているとして引用符のすべてをレンダリングする、すなわち、再びコメントと私は

ここでフィドル、私が作成

https://jsfiddle.net/p13c8L2w/2/

var QUOTES = [{ 
    "quote": "Success is not final; failure is not fatal: It is the courage to continue that counts.", 
    "author": "Winston S. Churchill" 
}, { 
    "quote": "Don't be afraid to give up the good to go for the great.", 
    "author": "John D. Rockefeller" 
}, { 
    "quote": "I find that the harder I work, the more luck I seem to have.", 
    "author": "Thomas Jefferson" 
}, { 
    "quote": "Try not to become a man of success. Rather become a man of value.", 
    "author": "Albert Einstein" 
}, { 
    "quote": "o one thing every day that scares you.", 
    "author": "Anonymous" 
}, { 
    "quote": "If you really look closely, most overnight successes took a long time.", 
    "author": "Steve Jobs" 
}, { 
    "quote": "The real test is not whether you avoid this failure, because you won't. It's whether you let it harden or shame you into inaction, or whether you learn from it; whether you choose to persevere.", 
    "author": "Barack Obama" 
}, { 
    "quote": "The successful warrior is the average man, with laser-like focus.", 
    "author": "Bruce Lee" 
}, { 
    "quote": "If you really want to do something, you'll find a way. If you don't, you'll find an excuse.", 
    "author": "Jim Rohn" 
}, { 
    "quote": "Be the type of person that when your feet hit the floor in the morning the devil says,aww shit.. they are up", 
    "author": "Dwayne (The Rock) Johnson" 
}, { 
    "quote": "Many of life's failures are people who did not realize how close they were to success when they gave up", 
    "author": "Thomas Edison" 
}, { 
    "quote": "Opportunities don't happen. You create them", 
    "author": "Chris Grosser" 
}, { 
    "quote": "I would rather risk wearing out than rusting out.", 
    "author": "Theodore Roosevelt" 
}, { 
    "quote": "When you play, play hard; when you work, don't play at all.", 
    "author": "Theodore Roosevelt" 
}]; 


var i = 0; 
var quotePara = document.getElementById("quotePara"); 
var getQuote = document.getElementById("getQuote"); 

// Request to get json data where the quotes are located 
getQuote.addEventListener("click", function() { 
    renderHTML(QUOTES); 
    // if the current index is the end restart back at 0 
    if (i===QUOTES.length) i=0; 
}); 


function renderHTML(data) { 
    var htmlString = ""; 
    var htmlAuthor = ""; 

    htmlString = data[i].quote; 
    htmlAuthor = data[i].author; 
    // i'm just fetching the next quote, for a random quote I would just use 
    // some random number logic from 0-length of quotes, 
    i++; 
    // I'm just building some html to show the quote 
    quotePara.innerHTML= ["<h2>", htmlString, "</h2>", htmlAuthor].join(""); 

} 
+0

目的は以下を一緒に使って、あなたがjsフィドルの下で行ったことを正確に行うことです。私はAPI /データページからJavaScriptを介して外部情報を取得し、ボタンをクリックするたびにhtmlに出力する必要があります。ボタンをクリックすると、古いテキストが削除され、配列内のデータの次の位置に置き換えられます。 – GauchoRoger

+0

ボタンがクリックされるたびにデータが来る場合は、データをどのように表示するのですか?変更されるので、1つのランダムな見積もりを選択しますか? – MartinWebb

+0

ボタンをクリックしたときにapiコールを行うには、ajaxコールが300〜500ms以上かかるため、前もってやりとりができますか? @ kooroosh-safeashrafi。 – MartinWebb

0

が調整されます通話機能renderHTML

との単純なループは、ここに私のバイオリンです: jsfiddle

var QUOTES = [{ 
 
    "quote": "Success is not final; failure is not fatal: It is the courage to continue that counts.", 
 
    "author": "Winston S. Churchill" 
 
}, { 
 
    "quote": "Don't be afraid to give up the good to go for the great.", 
 
    "author": "John D. Rockefeller" 
 
}, { 
 
    "quote": "I find that the harder I work, the more luck I seem to have.", 
 
    "author": "Thomas Jefferson" 
 
}, { 
 
    "quote": "Try not to become a man of success. Rather become a man of value.", 
 
    "author": "Albert Einstein" 
 
}, { 
 
    "quote": "o one thing every day that scares you.", 
 
    "author": "Anonymous" 
 
}, { 
 
    "quote": "If you really look closely, most overnight successes took a long time.", 
 
    "author": "Steve Jobs" 
 
}, { 
 
    "quote": "The real test is not whether you avoid this failure, because you won't. It's whether you let it harden or shame you into inaction, or whether you learn from it; whether you choose to persevere.", 
 
    "author": "Barack Obama" 
 
}, { 
 
    "quote": "The successful warrior is the average man, with laser-like focus.", 
 
    "author": "Bruce Lee" 
 
}, { 
 
    "quote": "If you really want to do something, you'll find a way. If you don't, you'll find an excuse.", 
 
    "author": "Jim Rohn" 
 
}, { 
 
    "quote": "Be the type of person that when your feet hit the floor in the morning the devil says,aww shit.. they are up", 
 
    "author": "Dwayne (The Rock) Johnson" 
 
}, { 
 
    "quote": "Many of life's failures are people who did not realize how close they were to success when they gave up", 
 
    "author": "Thomas Edison" 
 
}, { 
 
    "quote": "Opportunities don't happen. You create them", 
 
    "author": "Chris Grosser" 
 
}, { 
 
    "quote": "I would rather risk wearing out than rusting out.", 
 
    "author": "Theodore Roosevelt" 
 
}, { 
 
    "quote": "When you play, play hard; when you work, don't play at all.", 
 
    "author": "Theodore Roosevelt" 
 
}]; 
 

 

 

 

 
var pageCount = -1; 
 
var getQuote = document.getElementById("getQuote"); 
 

 
// Request to get json data where the quotes are located 
 
getQuote.addEventListener("click", function() { 
 
    if (pageCount===QUOTES.length) pageCount=-1; 
 
    pageCount++; 
 
\t renderHTML(pageCount,QUOTES); 
 
}); 
 

 

 

 
function renderHTML(i,data) { 
 
    var htmlString = ""; 
 
    var htmlAuthor = ""; 
 

 
    htmlString = data[i].quote; 
 
    htmlAuthor = data[i].author; 
 

 
\t document.getElementById("quote").innerText = htmlString; 
 
    document.getElementById("author").innerText = htmlAuthor; 
 
\t document.getElementById("page-num").innerText = i; 
 
}
<div> 
 
    <span id="quote"></span> 
 
</div> 
 
<div> 
 
    <span id="author"></span> 
 
</div> 
 
<div> 
 
    <span id="page-num"></span> 
 
</div> 
 
<div> 
 
    <button id="getQuote"class="btn btn-primary">Get Quote</button> 
 
</div>

あなたがループを必要といけない場合pageCount!=QUOTES.length

+0

あなたのコードは本当に役に立ちます。私がしようとしているのは、JSONデータを使って外部ファイルからデータを取得することです。私はjsファイル内でそれをしようとすることができますが、私のプロジェクトの一部は、APIまたはJSONファイルから情報を取得することです。 – GauchoRoger

+0

問題がJSONデータを取得している場合は、この[リンク](https://www.w3schools.com/js/tryit.asp?filename=tryjson_http)をお読みください。何か問題があった場合はこれを再生する –

関連する問題