从json选项生成html

时间:2013-10-08 06:20:43

标签: jquery

我正在尝试从var options = {}动态创建标签html数据。

我遇到tabs_html()函数,我必须迭代选项并为html.see创建嵌套数据。

我不想在js中使用html代码,而是使用$('<ul/>'$('<li/>'等对象创建它。

JS: JSFIDDLE

var structure = [
{
    "title": "tabs-1",
    "data": {
        "type": "t1",
        "title": "title hover"
    },
    "content": "Some Content"
},
{
    "title": "tabs-2",
    "data": {
        "type": "t2",
        "title": "title2 hover"
    },
    "content": "Some Content2"
}];

function tabs_html(structure) {
    var id = "tabs";
    var $wrapper_div = $('<div/>', {
        id: id
    });
    $.each(structure) {
        // make ul li and div
        // Not use html , instead use objects like $('<ul/>' and $('<li/>'
        // id of li`s will be id+_1 id+2 etc
    }
    $wrapper_div.append(above_each_data)
    return $wrapper_div;
}

$("body").append(tabs_html(structure));

示例HTML输出:

<!-- Sample Output 
<div id="tabs">
    <ul>
        <li><a href="#tabs-1" data-type="t1" data-title="title hover" >tabs-1</a> </li>
        <li><a href="#tabs-2" data-type="t2" data-title="title2 hover" >tabs-2</a> </li>
    </ul>
    <div id="tabs-1"></div>
    <div id="tabs-2"></div>
</div>
-->

2 个答案:

答案 0 :(得分:1)

我希望这可以帮助你:)。

var structure = [
    {
        title: "tabs-1",
        data: {
            type: "t1",
            title: "title hover"
        },
        content: "Some Content"
    }, {
        title: "tabs-2",
        data: {
            type: "t2",
            title: "title2 hover"
        },
        content: "Some Content2"
    }
];

function tabs_html(structure) {
    var $wrapper_div = $('<div/>').attr('id', 'tabs');
    var $list = $("<ul/>");
    $wrapper_div.append($list);
    $.each(structure, function(i, spec){
        var $tab = $("<div/>")
            .attr('id', spec.title)
            .text(spec.content);
        var $item = $("<li/>");
        var $link = $("<a/>")
            .attr('href', '#'+spec.title)
            .attr('data-type', spec.data.type)
            .attr('data-title', spec.data.title)
            .text(spec.title);
        $item.append($link);
        $list.append($item);
        $wrapper_div.append($tab);
    });
    return $wrapper_div;
}

$("body").append(tabs_html(structure));

JSFiddle

答案 1 :(得分:0)

您可以使用以下js函数生成html代码。

var newElm = function(obj) {
  // If not a good JSON, dont do anything
  if (!obj || !obj.type) {
    return;
  }
  // Create the DOM element as per type attribute
  var elm = document.createElement(obj.type), prop;
  console.log('TYPE:' + obj.type);
  // For all properties in the JSON
  for (prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      // If it is type, no need to handle, already done. Skip and continue.
      if (prop === 'type') {
        console.log('Skip TYPE!');
        continue;
      }
      // It is content, create the content
      if (prop === 'content') {
        // If the value is string, create a text node
        if (typeof obj[prop] === 'string' ||
    typeof obj[prop] === 'number') {
          console.log('CONTENT is Text:' + obj[prop]);
          elm.appendChild(document.createTextNode(obj[prop]));

        }
        // If it is a list, iterate and handle recursively
        else if (Array.isArray(obj[prop])) {
          console.log('CONTENT is List:' + JSON.stringify(obj[prop]));
          var tempArray = obj[prop];
          var i = 0,
            l = tempArray.length;
          for (; i < l; i++) {
            // Fixed for a Node appendChild error
            if (typeof tempArray[i] === 'string') {
              elm.innerHTML += tempArray[i];
            } else {
              elm.appendChild(newElm(tempArray[i]));
            }
          }
        }
        // Otherwise its an object, handle recursively
        else {
          console.log('CONTENT is Element:' + JSON.stringify(obj[prop]));
          elm.appendChild(newElm(obj[prop]));
        }
      }
      // Otherwise it is an attribute, add the attribute 
      else {
        elm.setAttribute(prop, obj[prop]);
      }
    }
  }
  return elm;
};

示例输入JSON如下所示。

var innerhtml = {
  type: 'b',
  content: ['This is BOLD text.', {
    type: 'i',
    content: ' Italics came from Italy? Its 35px and bold too.',
    style: 'font-size:35px;'
  }]
};

var htmlArr = {
  type: 'div',
  content: {
    type: 'p',
    content: ['Simple text with no formatting.', innerhtml, {type : 'img', src : '//www.gravatar.com/avatar/476914f28548ce41b3b7b2c5987720a9/?default=&s=64'}]
  }

};