2016-11-09 70 views
0

我正在循環一個數組,但我得到了數組長度的多個實例。有沒有在 -jQuery什麼是解決這個`關閉`的正確方法

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

+0

問題在'newHtml'功能 –

+0

那是什麼?你能弄清楚嗎? – 3gwebtrain

+0

將索引作爲參數傳遞給'newhtml(value);'。所以它變成'newhtml(index);' –

回答

1

他們沒有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>

0

您的代碼沒有按預期工作,因爲瀏覽器「修復」了您的標記並添加了另一個TBODY元素。

無論是固定的標記,或者使TBODY身份:

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

,改變newhtml到:

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

另外,不要避免closures。他們是一個好事 :)

+0

得到相同的結果,你可以更新與工作示例? – 3gwebtrain

相關問題