I am looping an array, but I am getting multiple instance of array length. is there any in-
var array = [{ name: 'name1', value: [1, 2, 3, 4] }, { name: 'name2', value: ['a', 'b', 'c', 'd'] }, { name: 'name3', value: ['a', 'b', 'c', 'd'] }]; var makeDropDown = function() { var newhtml = function(value) { var name = $('<td/>', { text: value.name }); var build = $('<tr/>').append(name).append($('<td/>')); $("tbody").append(build); } if (!array.length) return; $.each(array, function(index, value) { newhtml(value); //my try to avoid clousure not works! }) } makeDropDown();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <theader> <th>S.No</th> <th>Name</th> </theader> <tbody></tbody> <tfooter></tfooter> </table>
build way to avoid this in jQuery?
Their is no theader
and tfooter
it must be thead
and tfoot
var array = [{ name: 'name1', value: [1, 2, 3, 4] }, { name: 'name2', value: ['a', 'b', 'c', 'd'] }, { name: 'name3', value: ['a', 'b', 'c', 'd'] }]; var makeDropDown = function() { var newhtml = function(value) { var name = $('<td/>', { text: value.name }); var build = $('<tr/>').append(name).append($('<td/>')); //console.log(build); $("tbody").append(build); } if (!array.length) return; $.each(array, function(index, value1) { newhtml(value1); //my try to avoid clousure not works! }) } makeDropDown();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <thead> <th>S.No</th> <th>Name</th> </thead> <tbody></tbody> <tfoot></tfoot> </table>
Your code is not working as expected, because the browser "fixes" your markup and adds another TBODY
element.
Either fix the markup, or make the tbody identifiable:
<tbody id="root"></tbody>
and change the newhtml to:
...
$("tbody#root").append(build);
Also, do not avoid closures . They be a good thing :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.