如何根据内容类型在html格式之间切换?

时间:2015-10-21 09:00:43

标签: javascript jquery css json

我正在寻找一种解决方案,如何在多种html格式之间切换,具体取决于我的JSON中存储的内容类型。

我现在使用AJAX和JSON填写html格式:format-text.html

      $.ajax({
                    url: 'api/datacontent.json',
                    dataType: 'json',
                    success: function(data) {

                        root.dataArr = data;
                        root.objectArr = root.dataArr.content;
                        root.timeEvent;     
                        root.triggeredId = -1; 


                        $.get('directives/format-text.html', function(response){
                            console.log('succes');
                        })

                        .done(function (response) {
                              // Here I fill in the blanks with a for loop
                        }

                        .fail(function (response) {
                             console.dir(response); 
                        });
}

JSON:

{
        "title":    "Data content",
        "content":  [
            {
                "type" :        "youtube",
                "timeTrigger":  5,
                "title":        "Youtube",
                "subtitle":     "YouTube Channel",
                "picture" :     "images/content/london.jpg",
                "text":         "Visit their YouTube channel here.",
            },{
                "type" :        "location",
                "timeTrigger":  25,
                "title":        "London",
                "google":       "https://www.google.nl/maps/place/Londen,+Verenigd+Koninkrijk/@51.5340878,-0.0978221,12z/data=!4m2!3m1!1s0x47d8a00baf21de75:0x52963a5addd52a99"
            },{
                "type":         "text",
                "timeTrigger":  34,
                "title":        "Sherlock Holmes",
                "subtitle":     "Detective",
                "picture" :     "images/content/sherlockholmes.jpg",
                "text":         "Sherlock Holmes is a fictional detective created by British author Sir Arthur Conan Doyle. Holmes is known for his astute logical reasoning, his ability to adopt almost any disguise, and his use of forensic science to solve difficult cases.",
                "readmore":     "https://en.wikipedia.org/wiki/Sherlock_Holmes"
            }

如您所见,我使用format-text.html填写内容。但我的JSON文件包含多种类型的内容,如位置,文本和外部链接,每种类型都有不同的CSS样式。 如何在这些html内容之间切换并填写正确的内容块?

请留意一些建议。提前谢谢。

1 个答案:

答案 0 :(得分:1)

这有点混乱,你没有告诉我们你想如何在视图中对这些数据类型进行分类。

无论如何,如果API处理单个列表中的所有内容,那么您可以将结果分类到新数组中。

var formattedArr = {
  'videos' : [],
  'locations' : [],
  'texts' : []
};

for( var i =0; i <= dataContent.content.length; i++ ) {
  switch( dataContent.content[i].type ) {
    case 'youtube' : formatedArr.videos.push( dataContent.content[i] ); break;
    case 'location' :formatedArr.locations.push( dataContent.content[i] ); break;
    case 'text' : formatedArr.texts.push( dataContent.content[i] );
  }
}

然后您可以轻松地遍历各种类型。当然,如果API能够为您提供所需的格式,那会更好。