如何用json数据动态构造html标签属性?

时间:2013-06-11 11:31:01

标签: javascript jquery

我在名为 test 的变量中有(严格)json数据。我正在构建html元素动态,我还希望将 json数据插入到元素属性中。

var templateHtml = "":
    $.each(loopValues, function(Key, Value) { // Loops which constructs dynamic data
        var test = '{"type": "page"}';  // this is the json data which need to be appended as data-all attribute value.
        templateHtml = templateHtml.concat("<a data-all="+ test +" href='javascript:;' class='icon' id='TestTt'></a>");
    }
$("#sortable1").html(templateHtml);

执行这些行后,当我看到构造的元素时,它完全被扰乱了。如何在元素属性中获得格式良好的json数据?

enter image description here

不想在构造html后使用jquery在属性上附加json数据。我想在html构建时使用这个功能。

我提到过 http://gabrieleromanato.name/jquery-binding-animation-data-to-elements-with-json/ http://api.jquery.com/jQuery.parseJSON/

任何想法?

3 个答案:

答案 0 :(得分:2)

首先,您的代码会遗漏一些语法元素:

var templateHtml = ""; // use ; not :
$.each(loopValues, function (Key, Value) { // Loops which constructs dynamic data
    var test = '"{type": "page"}'; // this is the json data which need to be appended as data-all attribute value.
    templateHtml = templateHtml.concat("<a data-all=" + test + " href='javascript:;' class='icon' id='TestTt'></a>");
}); //close the loop call

然后,在附加测试变量时,需要在测试变量周围添加单引号。我建议你选择在哪里使用单引号或双引号并永久坚持选择。我个人在HTML中使用双引号,在JS中使用单引号:

var templateHtml = '';
$.each(loopValues, function (Key, Value) { // Loops which constructs dynamic data
    var test = "{type: 'page'}"; // this is the json data which need to be appended as data-all attribute value.
    //since its JSON i use single quote inside but double outside.
    templateHtml = templateHtml.concat('<a data-all="' + test + '" href="javascript:;" class="icon" id="TestTt"></a>');
});

FIDDLE here

答案 1 :(得分:1)

您可以将json保留在没有data-属性的DOM中,只需使用:

$("#sortable1").html("<a href='javascript:;' class='icon' id='TestTt'></a>");
$( "#sortable1 > a" ).data( 'all', test );

根据jQuery .data() API。数据值可以是任何JavaScript类型。

要获得此JSON,您只需要写:

console.log( $( "#sortable1 > a" ).data( 'all' ) );

<强>更新

但更好的是在创建过程中添加数据:

$.each(loopValues, function(Key, Value) { // Loops which constructs dynamic data
    $( "#sortable1" ).append( $( "<a/>" ).addClass( "icon" ).data( "all", {"type": "page"} ).attr( "id", "TestTt" ) );
});

答案 2 :(得分:1)

您需要的是使用jQuery创建元素,并使用json作为参数。

例如创建一个简单的表

var $table = new $('<table>', { 'cellpadding' : '5', 'cellspacing' : '4' });
var $tr = new $('<tr>');
var $td = new $('<td>', { 'class' : 'test' });
$td.text('cell contents');
$tr.append($td);
$table.append($tr);

$('body').append($table);