django django - 5 months ago 15
jQuery Question

generate html from json options

I am trying to create tabs html data dynamically from

var options = {}
.

I am stuck at
tabs_html()
function where i have to iterate over options and created nested data for html.see below.

I dont want to use html code in js rather create it using objects like
$('<ul/>'
and
$('<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));


Sample HTML Output:

<!-- 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>
-->

Answer

I hope this help you :)

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