jQuery修复这个`closure`的正确方法是什么

时间:2016-11-09 10:20:50

标签: jquery foreach

我正在循环一个数组,但是我得到了多个数组长度的实例。是否有 -

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>

构建在jQuery中避免这种情况的方法吗?

2 个答案:

答案 0 :(得分:1)

他们不是struct Event{ uint8_t eventId; uint8_t * data; const char * description; }; #define EVENT_REGISTER(eventName, desc)\ static Event eventName = {.eventId = __COUNTER__, .data = 0, .description = desc } EVENT_REGISTER(Timer_5, "Timer 5 hZ"); theader必须是tfooterthead

&#13;
&#13;
tfoot
&#13;
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();
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的代码未按预期运行,因为浏览器&#34;修复&#34;您的标记并添加另一个TBODY元素。

修复标记,或使tbody可识别:

<tbody id="root"></tbody>

并将newhtml更改为:

...
$("tbody#root").append(build);

此外,请勿避免 closures。他们是 好事 :)

相关问题