这是我的 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"}基本上,我希望每天的数据显示在单独的 div/列中。因此,我对该数据进行了以下 HTML 设置: <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 脚本的不同版本来向 div 提供数据:var outputTue = document.getElementById('outputWed');var ajaxhttp = new XMLHttpRequest();var url = "URL_TO_JSON";ajaxhttp.send(null);因此,任何单个脚本/div/ID 都会将数据填充到正确的列中。我尝试 getElementbyID向同一个脚本添加多个,但只能填充一个。然后我尝试了两个脚本,除了更改“day”变量之外,它们基本上是相同的。这种方法有效(第一个 div 显示了相同数据的多个副本,第二列是正确的)。添加 5 个脚本根本不起作用。如何将数据放入单独的 div/列/ID 中?
1 回答
白衣染霜花
TA贡献1796条经验 获得超10个赞
循环遍历内容,并将属性名称转换为对应的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 关注
- 75 浏览
添加回答
举报
0/150
提交
取消