如何在javascript对象中循环并在html中显示值

How to loop through javascript object and display value in html

本文关键字:html 显示 循环 javascript 对象      更新时间:2023-09-26

我是新的javascript,我需要帮助。我想在js文件中存储一些视频,格式如下。

这是videoos .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>

**这里是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>

我目前手动更新的html,但它需要太多的时间和文件变得更大。我想只是在videos.js文件上更新新的视频,并自动生成html和样式。

如果你有更好的方法,请告诉我。否则,请帮忙。谢谢。

请看下面的链接。我已经生成了您的整个代码使用多个循环。它包含了一个库:jQuery。它被用来使代码更短。

演示

这是创建数组和对象的方法:

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'
    }
  }
}

然后遍历它:

$.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>'; 
        });
    });
});

是时候了解for循环了!https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

对于你的特定内容,有很多方法可以做到这一点,我不打算为你解决这个问题,但让我们以你的样本数据为例:

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

key可以被命名为任何东西,但它是每个视频的关键'240,360等'

现在,上面的示例将只在该节点上循环。由于您有多个嵌套节点,您将不得不提出一个系统来遍历它们,如何做到这一点取决于您。

for循环中,您还可以通过这样做创建新的锚标记。

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

将值传递给变量并使用for in循环和document.write或DOM操作。

更多:

  • http://www.w3schools.com/js/js_loop_for.asp
  • http://www.w3schools.com/js/js_output.asp
  • http://www.w3schools.com/js/js_htmldom_nodes.asp

我建议以不同的方式构建您的代码。例如,你的对象可以是一个对象数组。

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

你可以使用jquery迭代这个对象…或者简单的javascript。使用规范js:

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

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

本质上是开发一个对象数组。它们可以在foreach循环中访问,如"object name"点"object property"。然后将它附加到HTML文档中。

我更喜欢javascript对象层次结构,比如:{name:"根",子:[{名称:"家庭",子女:[{name:"Children", Children:[]},{name:"Parent", children:[]})},{名称:"每月",儿童:[{name:"January", children:[]},{name:"February", children:[]}]}]}

然后一个更加未来证明的循环,无论是递归的还是非递归的,都可以通过,而不必担心类别的名称或重新编码。

同样,使用Ember.js这样的东西将一个对象赋值给一个html模板可以方便地输出html,但不是必需的。

如果你的数据js变得太大,我会诉诸于与服务器交谈并通过记录分页,而不是硬编码js。

我的处理方法是使用jQuery。每个方法在对象上进行交互。

HTML:

<body>
    <div id="videos">
        <!-- VIDEOS GET INSERTED HERE -->
    </div>
</body>
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);    
});

这里是jsFiddle: http://jsfiddle.net/4u505hcq/1/

重要的是创建对象并正确理解结构。其余部分很简单,for循环

  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);
                    }
                }
            }
        }
    }
}