2016-11-09 7 views
0

私は配列をループしていますが、配列の長さのインスタンスが複数取得されています。 jQueryのでこれを回避するためのいずれかのインjQueryこの `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>

ビルド方法はありますか?

+0

問題 –

+0

ことが何であるかでなければなりません?どうぞお分かりですか? – 3gwebtrain

+0

引数を 'newhtml(value);'に渡します。したがって、それは 'newhtml(index);となります。 –

答えて

1

彼らの何theaderがなく、tfooterそれはあなたの `newHtml`機能で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

関連する問題