samedi 25 juin 2016

How to apply attribute using Jquery "appendTo "


I am writing a code that reads in a JSON data and then create a table using appendTo. I am trying to apply an attribute "href" to a table field. I have tried multiple ways, but I am unable to see the href inside the generated html code. I am trying to have something like this in the generated code: <td><a href="#"> key1</a></td What would be the best way to generate this kind of code? http://jsfiddle.net/charles30hk/b3cqtnur/ var data = {"key1":{"key11":"value11", "key12":"value12"}, "key2":"value2", "key3":"value3", "key4":"value3", "key5":{"key51":"value11", "key52":"value12", "key53":{"key531":"value","key52":"value12"}, }, }; function loop(obj, ul,nested=0) { $.each(obj, function(key, val) { if($.isPlainObject(val)) { //$("<tr>").appendTo(ul) for (i=0;i<nested;i++) { $("<td>").append().appendTo(ul) } $("<td class=link>").text(key).appendTo(ul) //$("td").last().attr("href","#") /*var ul2 = $("<td>").text("hello").appendTo( $("<tr>").appendTo(ul) ); */ //var u12 = $("<tr>").appendTo(ul) if (i==0){ $("<tr class=parent>").appendTo(ul) } else{ $("<tr>").appendTo(ul) } //$("<td>").appendTo(ul) loop(val, ul,nested+1); } else { //$("<tr>").appendTo(ul) for (i=0;i<nested;i++) { $("<td>").appendTo(ul) } $("<td>").text(key).appendTo(ul) //ul+="<td>"+key+"</td>" $("<td>", { id: key }).text(val).appendTo(ul); if (i==0){ $("<tr class=parent>").appendTo(ul) } else{ $("<tr>").appendTo(ul) } } }); } $(function(){ $("#products").on("click","a",function(e) { e.preventDefault(); $(this).closest("tr").nextUntil(".parent").toggleClass("open"); }); });

Aucun commentaire:

Enregistrer un commentaire