這是我的 JSON 示例:{ "Monday": [ { "type": "menu_category", "recipe": "Soup" }, { "type": "menu_item", "recipe": "Monday Soup 1" }, { "type": "menu_item", "recipe": "Monday Soup 2" }], "Tuesday": [ { "type": "menu_category", "recipe": "Soup" }, { "type": "menu_item", "recipe": "Tuesday Soup 1" }, { "type": "menu_item", "recipe": "Tuesday Soup 2" }],... same format for "Wednesday", "Thursday", and "Friday"}基本上,我希望每天的數(shù)據(jù)顯示在單獨(dú)的 div/列中。因此,我對(duì)該數(shù)據(jù)進(jìn)行了以下 HTML 設(shè)置: <div class="monday"> <p class="weekday">Monday</p> <div id="outputMon"></div> <script src="scriptM.js"></script> </div> <div class="tuesday"> <p class="weekday">Tuesday</p> <div id="outputTue"></div> <script src="script2.js"></script> </div> <div class="wednesday"> <p class="weekday">Wednesday</p> <div id="outputWed"></div> <script src="scriptW.js"></script> </div> <div class="thursday"> <p class="weekday">Thursday</p> <div id="outputThu"></div> <script src="scriptTh.js"></script> </div> <div class="friday"> <p class="weekday">Friday</p> <div id="outputFri"></div> <script src="scriptF.js"></script> </div>我有以下 js 腳本的不同版本來(lái)向 div 提供數(shù)據(jù):var outputTue = document.getElementById('outputWed');var ajaxhttp = new XMLHttpRequest();var url = "URL_TO_JSON";ajaxhttp.send(null);因此,任何單個(gè)腳本/div/ID 都會(huì)將數(shù)據(jù)填充到正確的列中。我嘗試 getElementbyID向同一個(gè)腳本添加多個(gè),但只能填充一個(gè)。然后我嘗試了兩個(gè)腳本,除了更改“day”變量之外,它們基本上是相同的。這種方法有效(第一個(gè) div 顯示了相同數(shù)據(jù)的多個(gè)副本,第二列是正確的)。添加 5 個(gè)腳本根本不起作用。如何將數(shù)據(jù)放入單獨(dú)的 div/列/ID 中?
1 回答

白衣染霜花
TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
循環(huán)遍歷內(nèi)容,并將屬性名稱轉(zhuǎn)換為對(duì)應(yīng)的div ID。
for (var day in jcontent) {
if (day.match(/day$/)) {
var divid = 'output' + day.substr(0, 3);
var output = document.getElementById(divid);
var newContent = jcontent[day].map(({type, recipe}) => `<p class="${type}">${recipe}</p>`).join("");
output.innerHTML = newContent;
}
}
- 1 回答
- 0 關(guān)注
- 111 瀏覽
添加回答
舉報(bào)
0/150
提交
取消