简体   繁体   English

循环使用数组填充网页而不使用HTML但使用Javascript

[英]Loop in an array to fill a web page without using HTML but Javascript

I'm studying Javascript and I find an interesting question which ask me to Render the model data from library.js in the library, artists and albums view. 我正在研究Javascript,发现一个有趣的问题,问我要在库,艺术家和专辑视图中从library.js渲染模型数据。 This means that instead of serving static HTML, I will iterate through every track to create the library view, through every artist to create the artists view and through every album to create the albums view. 这意味着我将不遍历静态HTML,而是遍历每条轨道来创建库视图,遍历每位艺术家来创建艺术家视图,并遍历每张专辑来创建专辑视图。 Since tracks reference artists and albums by _id, I will have to resolve these first in order to populate the library view. 由于通过_id跟踪参考艺术家和专辑,因此我必须首先解析它们才能填充库视图。 As ip I have that since all pages are going to use the same app.js, it will be convenient to add a different class in the body of my HTML pages and based on this class render the correct view. 作为ip,由于所有页面都将使用相同的app.js,因此在HTML页面的主体中添加不同的类并基于该类呈现正确的视图将很方便。 For example the body of the library view can have the class library. 例如,库视图的主体可以具有类库。 This exercise is based on the creation of a music player. 此练习基于音乐播放器的创建。 I have already create some code to store the tracks and the artists using two different javascript files (what the exercise asks to me). 我已经创建了一些代码,以使用两个不同的javascript文件(练习向我询问的内容)来存储曲目和艺术家。 Then I have this two files: 然后我有这两个文件:

LIBRARY.JS 图书馆

model.tracks.push('t1', 'Live like therse no tomorrow', 'Selena Gomez', '', 251);
model.tracks.push('t2', 'The scientist', 'ColdPlay', '', 250);
model.tracks.push(_id, title, artist, file, duration);

Where model is: 模型在哪里:

var model = {
user: [],
artists: [],
albums: [],
playlist: [],
tracks: []
};

APP.JS APP.JS

window.onload = function(){
// implement the logic to render the views here. Of course, you can call other functions
// to avoid having a huge function
var myStringArray = model.tracks;
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    alert(myStringArray[i]);
    //Do something
}

Is this idea right for my code or I have to change it? 这个想法适合我的代码还是必须更改? How can transport everything in my web page only working on the javascript?? 如何仅在javascript上才能传输我网页中的所有内容?

  1. your idea is basically right (the model has to be filled with data dynamically - JSON, make a render function, which would be called from onload handler) 您的想法基本上是正确的(模型必须动态填充数据-JSON,创建一个渲染函数,可以从onload处理程序中调用)

  2. I suggest to call REST services delivering the JSON data (large data, changing data), or create a string variable with deflated JSON data and inflate it by the script (static data, offline app) 我建议调用提供JSON数据(大数据,更改数据)的REST服务,或创建带有缩小的JSON数据的字符串变量,然后通过脚本(静态数据,离线应用)对其进行充气

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM