简体   繁体   English

如何遍历javascript对象并在html中显示值

[英]How to loop through javascript object and display value in html

I am new to javascript and I need help with this. 我是javascript的新手,因此需要帮助。 I want to store a number of videos in a js file in the format I have it below. 我想以下面的格式在js文件中存储许多视频。

Here is the videos.js file 这是videos.js文件

 <script> videos { monthly { january { 240 : 'linktojanuary240.mp4', 360 : 'linktojanuary360.mp4', 480 : 'linktojanuary480.mp4', 720 : 'linktojanuary720.mp4' }, february { 240 : 'linktofebruary240.mp4', 360 : 'linktofebruary360.mp4', 480 : 'linktofebruary480.mp4', 720 : 'linktofebruary720.mp4' } }; family { children { 240 : 'linktochildren240.mp4', 360 : 'linktochildren360.mp4', 480 : 'linktochildren480.mp4', 720 : 'linktochildren720.mp4' }, parent { 240 : 'linktoparent240.mp4', 360 : 'linktoparent360.mp4', 480 : 'linktoparent480.mp4', 720 : 'linktoparent720.mp4' } }; }; </script> 

**And here is the index.html file ** **这是index.html文件**

 <html> <head> </head> <body> <h3> Monthly </h3> <h1>january</h1> <a href="linktojanuary240p.mp4" data-role="button" data-inline="true" data-mini="true">240p </a> <a href='linktojanuary360p.mp4' data-role="button" data-inline="true" data-mini="true">360p </a> <a href='linktojanuary480p.mp4' data-role="button" data-inline="true" data-mini="true">480p </a> <a href='linktojanuary720p.mp4' data-role="button" data-inline="true" data-mini="true">720p </a> <h1>february</h1> <a href="linktofebruary240p.mp4" data-role="button" data-inline="true" data-mini="true">240p </a> <a href='linktofebruary360p.mp4' data-role="button" data-inline="true" data-mini="true">360p </a> <a href='linktofebruary480p.mp4' data-role="button" data-inline="true" data-mini="true">480p </a> <a href='linktofebruary720p.mp4' data-role="button" data-inline="true" data-mini="true">720p </a> <h3> family </h3> <h1>children</h1> <a href="linktochildren240p.mp4" data-role="button" data-inline="true" data-mini="true">240p </a> <a href='linktochildren360p.mp4' data-role="button" data-inline="true" data-mini="true">360p </a> <a href='linktochildren480p.mp4' data-role="button" data-inline="true" data-mini="true">480p </a> <a href='linktochildren720p.mp4' data-role="button" data-inline="true" data-mini="true">720p </a> <h1>parent</h1> <a href="linktoparent240p.mp4" data-role="button" data-inline="true" data-mini="true">240p </a> <a href='linktoparent360p.mp4' data-role="button" data-inline="true" data-mini="true">360p </a> <a href='linktoparent480p.mp4' data-role="button" data-inline="true" data-mini="true">480p </a> <a href='linktoparent720p.mp4' data-role="button" data-inline="true" data-mini="true">720p </a> </body> 

I currently update the html manually but it takes too much time and the file gets bigger. 我目前正在手动更新html,但是它花费了太多时间,并且文件越来越大。 I would like to just update new videos on the videos.js file and have the html generated and styled automatically. 我只想在videos.js文件上更新新视频,并自动生成并设置样式的html。

If you have a better way I can do this, kindly let me know. 如果您有更好的方法可以做到这一点,请告诉我。 Otherwise, kindly help with that. 否则,请提供帮助。 Thanks. 谢谢。

Look at the link below. 请看下面的链接。 I have generated your whole code using multiple loops. 我已经使用多个循环生成了整个代码。 There is a library included: jQuery . 有一个包含的库: jQuery It's used to make the code shorter. 它用于使代码更短。

Demo 演示版

This is how you create arrays and objects: 这是创建数组和对象的方式:

var videos = {
  monthly: {
    january: {
      240: 'linktojanuary240.mp4',
      360: 'linktojanuary360.mp4',
      480: 'linktojanuary480.mp4',
      720: 'linktojanuary720.mp4'
    },
    february: {
      240: 'linktofebruary240.mp4',
      360: 'linktofebruary360.mp4',
      480: 'linktofebruary480.mp4',
      720: 'linktofebruary720.mp4'
    }
  },
  family: {
    children: {
      240: 'linktochildren240.mp4',
      360: 'linktochildren360.mp4',
      480: 'linktochildren480.mp4',
      720: 'linktochildren720.mp4'
    },
    parent: {
      240: 'linktoparent240.mp4',
      360: 'linktoparent360.mp4',
      480: 'linktoparent480.mp4',
      720: 'linktoparent720.mp4'
    }
  }
}

And then iterate over it: 然后遍历它:

$.each(videos, function(key, value) {
   html += "<h3>"+key+"</h3>";
    $.each(value, function(month, file) {
     html += "<h1>"+month+"</h1>";
        $.each(file, function(size, name) {
            html += '<a href="'+name+'" data-role="button" data-inline="true" data-mini="true">'+size+' </a>'; 
        });
    });
});

Time to learn about the for loop! 是时候学习for循环了! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/

There are a number of ways you can do this with your specific content, and i'm not going to solve this for you, but lets take your sample data for a second: 您可以通过多种方式对特定内容执行此操作,而我不会为您解决此问题,而是让您先获取示例数据:

for(var key in videos.monthly.january){
   // videos.monthly.january[key] will print out all your videos from january
}

key can be named anything but it is the key to each video '240, 360 etc' key可以命名为任何其他名称,但这是每个视频的键“ 240、360等”

Now, the example above will only loop over that one node. 现在,上面的示例将仅在该节点上循环。 Since you have multiple nested nodes you will have to come up with a system to loop through them all, how you do this is up to you. 由于您有多个嵌套节点,因此您将不得不想出一个系统来遍历所有这些嵌套节点,如何执行此操作取决于您自己。

In your for loop, you can also create new anchor tags by doing something like this. for循环中,您还可以通过执行以下操作来创建新的锚标记。

document.body.appendChild('<a href="'+videos.monthly.january[key]+'" data-role="button" data-inline="true" data-mini="true">'+key+'p </a>');

Pass value to variable and use for in loop and document.write or DOM manipulation. 将值传递给变量,并for in循环和document.write或DOM操作。

More here: 更多内容:

I would suggest structuring your code differently. 我建议以不同的方式构造您的代码。 for example your objects can be an array of objects. 例如,您的对象可以是对象数组。

var videos=[{
month:"jan",
240:"link",
360:"link"
},{
month:"feb",
240:"link2",
360:"link2"
}];

You can then itterate through this object using jquery...or simple javascript. 然后,您可以使用jquery ...或简单的javascript遍历此对象。 using norm js: 使用规范js:

videos.forEach(function(video){
var div=document.createElement('div');
div.textContent=video.month;
document.body.appendChild(div)
});

jquery: jQuery的:

videos.forEach(function(){
var div=$("<div>"+video.month+"<div>");
$(document.body).append(div);
});

Essentially, develop an array of objects. 本质上,开发一系列对象。 they can be accessed in a foreach loop like "object name" dot "object property". 可以在foreach循环中访问它们,例如“对象名称”点“对象属性”。 then just append it to the html document. 然后将其附加到html文档中。

Me, I would prefer a javascript object hierarchy, like: { name:"root", children:[ { name:"Family", children:[ { name:"Children", children:[] }, { name:"Parent", children:[] } ] }, { name:"Monthly", children:[ { name:"January", children:[] }, { name:"February", children:[] } ] } ] }, 我,我希望使用JavaScript对象层次结构,例如:{名称:“ root”,子代:[{名称:“家庭”,子代:[{名称:“儿童”,子代:[]},{名称:“父代“,儿童:[]}]},{名称:“每月”,儿童:[{名称:“一月”,儿童:[]},{名称:“二月”,儿童:[]}]}]},

Then a more future proof loop, either recursive or not could go through without worrying about the names of your categories or having recode it. 然后,可以进行一个更将来的证明循环,无论是递归的还是不循环的,而不必担心类别的名称或重新编码。

Also, using something like Ember.js to assign an object to a html template would make it convenient to spit out the html, but not essential. 另外,使用Ember.js之类的对象将对象分配给html模板将使吐出html变得很方便,但这不是必需的。

If your data js gets too big I'd resort to talking to a server and paginating through the records, rather than hardcoding the js. 如果您的数据js太大,我会求助于服务器并通过记录进行分页,而不是对JS进行硬编码。

Just 只是

The way I would handle would be to use the jQuery.each method to interate over the object. 我要处理的方法是使用jQuery.each方法插入对象。

HTML: HTML:

<body>
    <div id="videos">
        <!-- VIDEOS GET INSERTED HERE -->
    </div>
</body>

JAVASCRIPT: JAVASCRIPT:

var videos = {
    monthly: {
        january: {
            240: 'linktojanuary240.mp4',
            360: 'linktojanuary360.mp4',
            480: 'linktojanuary480.mp4',
            720: 'linktojanuary720.mp4'
        },
        february: 
        {
            240: 'linktofebruary240.mp4',
            360: 'linktofebruary360.mp4',
            480: 'linktofebruary480.mp4',
            720: 'linktofebruary720.mp4'
        }
    },    
    family: {
        children: {
            240: 'linktochildren240.mp4',
            360: 'linktochildren360.mp4',
            480: 'linktochildren480.mp4',
            720: 'linktochildren720.mp4'
        },
        parent: {
            240: 'linktoparent240.mp4',
            360: 'linktoparent360.mp4',
            480: 'linktoparent480.mp4',
            720: 'linktoparent720.mp4'
        }
    }
};

$(document).ready(function(){
    var html = "";
    // go through each item under videos...
    $.each(videos, function(itemName, item){
        html += ("<h3>" + itemName + "</h3>");
        // go through each item under item...
        $.each(item, function(subItemName, subItem){
            html += ("<h1>" + subItemName + "</h1>");
            // go through each item under subItem...
            $.each(subItem, function(linkNumber, linkValue){
                // create hyperlink...
                html += ("<a href=\"linkto" + subItemName + linkNumber + "p.mp4\" data-role=\"button\" data-inline=\"true\" data-mini=\"true\">" + linkNumber + "p</a>"); 
            });
        });
    });
    // insert final html into #videos...
    $("#videos").html(html);    
});

Here's the jsFiddle: http://jsfiddle.net/4u505hcq/1/ 这是jsFiddle: http : //jsfiddle.net/4u505hcq/1/

Important thing is creating the object and understanding your structure properly. 重要的是创建对象并正确理解您的结构。 Rest is simple for loops 休息很容易循环

  for(var category in videos){
            var h3 = document.createElement('h3');
            var categoryContent = document.createTextNode(category);
            h3.appendChild(categoryContent);
            document.body.appendChild(h3);
            for(var subcategory in videos[category]){
                var h1 = document.createElement('h1');
                var subcategoryContent = document.createTextNode(subcategory);
                h1.appendChild(subcategoryContent);
                document.body.appendChild(h1);
                for(videolink in videos[category][subcategory]){
                    var a = document.createElement('a');
                    var aContent = document.createTextNode(videolink); 
                    a.appendChild(aContent);
                    a.setAttribute('href',videos[category][subcategory][videolink]);
                    a.setAttribute('data-role','button');
                    a.setAttribute('data-inline','true');
                    a.setAttribute('data-mini','true');
                    document.body.appendChild(a);
                }
            }
        }
// 1. Use h2, under h1, h3 under h2 etc.
// 2. As said before, it's time to learn JS and HTML.
// 3. Your JSON object has some syntax errors (see the corrections below).
// 4.Enjoy


// JavaScript source code
var videos = {
    monthly: {
        january:
            {
                240: 'linktojanuary240.mp4',
                360: 'linktojanuary360.mp4',
                480: 'linktojanuary480.mp4',
                720: 'linktojanuary720.mp4'
            },

        february:
          {
            240: 'linktofebruary240.mp4',
            360: 'linktofebruary360.mp4',
            480: 'linktofebruary480.mp4',
            720: 'linktofebruary720.mp4'
          }
    },

    family: {
        children:
           {
            240: 'linktochildren240.mp4',
            360: 'linktochildren360.mp4',
            480: 'linktochildren480.mp4',
            720: 'linktochildren720.mp4'
           },
        parent:
            {
                240: 'linktoparent240.mp4',
                360: 'linktoparent360.mp4',
                480: 'linktoparent480.mp4',
                720: 'linktoparent720.mp4'

            }
    }

};

var body = $("body");
for (var p in videos) {
    if (videos.hasOwnProperty(p)) {
        var h1 = $("<h1>" + p + "</h1>");
        body.append(h1);
        for (var m in videos[p]) {
            if (videos[p].hasOwnProperty(m)) {
                var h2 = $("<h2>" + m + "</h2>");
                body.append(h2);
                for (var v in videos[p][m]) {
                    if (videos[p][m].hasOwnProperty(v)) {
                        var a = $("<a href='" + videos[p][m][v] + "' data-role='button' data-inline='true' data-mini='true'>" + v + "p </a><br/> ");
                        body.append(v);
                    }
                }
            }
        }
    }
}

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

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