3gwebtrain 3gwebtrain - 28 days ago 7
jQuery Question

jQuery what is the correct way to fix this `closure`

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?

Answer

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>