繁体   English   中英

jQuery修复此`closure'的正确方法是什么

[英]jQuery what is the correct way to fix this `closure`

我正在循环一个数组,但是正在获取多个数组长度的实例。 是否有任何-

 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中?

他们没有theadertfooter它必须是theadtfoot

 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> 

您的代码无法正常工作,因为浏览器“修复”了您的标记并添加了另一个TBODY元素。

修复标记,或使本体可识别:

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

并将newhtml更改为:

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

同样,不要避免 闭包 他们是一件好事 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM