2017-12-03 9 views
0

JSONファイルを見て、<div>のIDがJSONの "id"値と一致するかどうかに基づいて、適切なコンテンツをHTMLファイルに追加するJSループ(jQueryを使用)を作成します。これは、どのように多くのボックスが追加されるかに関係なく、容易にスケーラビリティがあり、機能する必要があります。JSONファイルを使用して動的にHTMLコンテンツを更新しますか?

<div class="box" id="1"> 
     <h1></h1> 
     <hr/> 
     <p></p> 
    </div> 
    <div class="box" id="2"> 
     <h1></h1> 
     <hr/> 
     <p></p> 
    </div> 
    <div class="box" id="3"> 
     <h1></h1> 
     <hr/> 
     <p></p> 
    </div> 

そして、各ボックスの要素の値を持つ別々のJSONファイル:基本的に

{ 
    "content": [ 
     { 
      "id": 1, 
      "header": "Box 1", 
      "para": "This is Box 1", 
      "other": "Another key that's not necessarily used for all boxes" 
     }, 
     { 
      "id": 2, 
      "header": "Box 2", 
      "para": "This is Box 2" 
     }, 
     { 
      "id": 3, 
      "header": "Box 3", 
      "para": "This is Box 3", 
      "other": "Another key that's not necessarily used for all boxes" 
     } 
    ] 
} 

Desired result.

を次のように


は私が設定したHTMLファイルを持っていますこれは私が探している結果です(いくつかの基本的なCSSスタイルが追加されています)。私はJSにまだかなり新たなんだと

$.getJSON('content.json', function (data) { 

    "use strict"; 

    var content = data.content; 

    $('#1 h1').html(content[0].header); 
    $('#2 h1').html(content[1].header); 
    $('#3 h1').html(content[2].header); 

    $('#1 p').html(content[0].para); 
    $('#2 p').html(content[1].para); 
    $('#3 p').html(content[2].para); 

}); 

詳細な答えが、理解されるだろうし、次のスクリプトは、明らかにかかわらず、このコードはそれほどスケーラブルではない、新しい<div>が追加されるたびに変更しなければなりません私が達成しようとしていることを正確に説明しているものは見つかりませんでした。

ありがとうございます! :)あなたが使用したいことはforEachループです

+1

こんにちは、新しい言語を学ぶときに、それがサブタスクに完全なタスクを分離することがしばしば良いことです。たとえば、 - あなたはJavaScriptを使用してループを作成する方法を知っていますか?それをテストして何かを出力するだけです(例えばconsole.logのループカウンター)。一度それが機能したら、ハードコードされた配列をループして、それをコンソールに印刷してみてください...次にJSONをループして印刷してみて、コンソールに印刷する代わりに、それをページの要素に挿入してから、最後に正しいページ要素に配置します。あなたはこれを行うことができます:) –

+1

そして、あなたはJqueryの使い方を学ぶ前にJavaScriptを学ぶべきです。実際にはjQueryを使用する必要はありません。 –

+0

@LucaKiebel、時には単純な問題を解決するために非常に大きなライブラリを導入するのは難しいことです。 Javascriptについてよく知っている方は、もう一方のJavascriptをいつ使うべきか、という良いアイデアがあります。多くのjavascript開発者と協力して、jQueryを最もよく使ったのは、JavaScriptを最初に学んだ人でした。彼らはすべて、jQueryが解決しようとする問題をよりよく理解していました。 –

答えて

1

、あなたはJSONファイルの内容の配列がどのくらい気にする必要はありません。その方法:

$.getJSON('content.json', function (data) { 

    "use strict"; 

    var content = data.content; 
    content.forEach(e => { 
     $("#"+e.id+" h1").html(e.header) 
     $("#"+e.id+" p").html(e.para) 
    }); 
}); 

ここでは、作業フィドルです:https://jsfiddle.net/qsrehpa2/1/

+0

パーフェクト、シンプルで理解しやすい、ありがとう! :) – Hexbob6

1

あなたはとてもなどの要素を埋めるために、現在のオブジェクトを使用してコンテンツをループすることができます

$.getJSON('content.json', function(data) { 
    "use strict"; 

    var content = data.content; 

    content.forEach(obj => { 
    $(`.box#${obj['id']}`) 
     .find('h1').text(obj['header']).end() 
     .find('p').text(obj['header']); 
    }); 
}); 

はここでローカルコピーをWiをどのように見えるかですthout使用してJSONは:

const content = [{ 
 
    "id": 1, 
 
    "header": "Box 1", 
 
    "para": "This is Box 1", 
 
    "other": "Another key that's not necessarily used for all boxes" 
 
    }, 
 
    { 
 
    "id": 2, 
 
    "header": "Box 2", 
 
    "para": "This is Box 2" 
 
    }, 
 
    { 
 
    "id": 3, 
 
    "header": "Box 3", 
 
    "para": "This is Box 3", 
 
    "other": "Another key that's not necessarily used for all boxes" 
 
    } 
 
]; 
 

 
content.forEach(obj => { 
 
    $(`.box#${obj['id']}`) 
 
    .find('h1').text(obj['header']).end() 
 
    .find('p').text(obj['para']); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="box" id="1"> 
 
    <h1></h1> 
 
    <hr/> 
 
    <p></p> 
 
</div> 
 

 
<div class="box" id="2"> 
 
    <h1></h1> 
 
    <hr/> 
 
    <p></p> 
 
</div> 
 

 
<div class="box" id="3"> 
 
    <h1></h1> 
 
    <hr/> 
 
    <p></p> 
 
</div>

1

あなたは、あなたのソリューションがスケーラブルになりたい言及したので、それが自動的にあなたのためのHTMLを作成するように私はjQueryのコードを書きました。

// Download the JSON file 
$.getJSON("content.json", function (data) { 
    // Loop through each JSON item 
    $.each(data.content, function (index, item) { 
     // Create and append HTML tags filled out with the data 
     $("body").append(
      $("<div>") 
       .attr("id", item.id) 
       .append($("<h1>").text(item.header)) 
       .append($("<hr>")) 
       .append($("<p>").text(item.para))); 
    }); 
}); 
1

これを少し試してみましょう。

私たちはHTMLテンプレートを使用して、データを挿入するためにできるだけ構造をデカップリングします。たとえば、h1h2に変更する場合は、javascriptを掘り起こす必要はありません。

私はボックスのリストであるので、これをリストにラップしました。それは純粋にオプションです。

/*GOing to hide the AJAX Call for the demo */ 
 
/*$.getJSON('content.json', function(data) { 
 
    "use strict"; 
 

 
    var content = data.content; 
 
*/ 
 

 
//Dummy Dump of our data; 
 
var content = [{ 
 
    "id": 1, 
 
    "header": "Box 1", 
 
    "para": "This is Box 1", 
 
    "other": "Another key that's not necessarily used for all boxes" 
 
    }, 
 
    { 
 
    "id": 2, 
 
    "header": "Box 2", 
 
    "para": "This is Box 2" 
 
    }, 
 
    { 
 
    "id": 3, 
 
    "header": "Box 3", 
 
    "para": "This is Box 3", 
 
    "other": "Another key that's not necessarily used for all boxes" 
 
    } 
 
]; 
 

 

 
//Set Up the template 
 
var s = $("#boxTemplate")[0].innerHTML.trim(); 
 
var holder = document.createElement('div'); 
 
holder.innerHTML = s; 
 
var boxTemplate = holder.childNodes 
 

 
content.forEach(obj => { 
 
    //Clone Template 
 
    var newItem = $(boxTemplate).clone(); 
 
    //Populate it 
 
    $(newItem).find(".head").html(obj['header']); 
 
    $(newItem).find(".bodyContent").html(obj['para']); 
 
    //Append it 
 
    $("#boxes").append(newItem); 
 
}); 
 

 
/* 
 
What would be the closure of the Ajax call 
 
}); 
 
*/
#boxes { 
 
    list-style-type: none; 
 
    padding: 0; 
 
} 
 

 
#boxes li { 
 
    width: 33%; 
 
    float: left; 
 
    border: 1px solid black; 
 
} 
 

 
#boxes>li:nth-child(3n+1) { 
 
    border-right: none; 
 
} 
 

 
#boxes>li:nth-child(3n+3) { 
 
    border-left: none; 
 
} 
 

 
#boxes .head { 
 
    border-bottom: 2px solid #999; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<ul id="boxes"> 
 
</ul> 
 
<!-- Ideally we'd use the new <template> tag here but IE support is no good --> 
 
<script type="text/template" id="boxTemplate"> 
 
    <li> 
 
    <h1 class="head"></h1> 
 
    <p class="bodyContent"> 
 
    </li> 
 
</script>