[英]return instruction stop my for-loop in javascript
當我使用for循環時,沒有任何問題
for (var h = 0; h < xt.length; h++) {
var heart = '';
console.log(xt[h]);
if (row[0] == xt[h]) {
heart = 'icon-heart';
} else {
heart = 'icon- heart1';
}
}
但是當我使用返回指令時,循環停止:
for (var h = 0; h < xt.length; h++) {
var heart = '';
console.log(xt[h]);
if (row[0] == xt[h]) {
heart = 'icon-heart';
} else {
heart = 'icon-heart1';
}
return '<i class="' + heart + '" onClick="addFAv(this)" data-id="' + row[0] + '" data-name="' + row[1] + '"></i> <a href="#" class="icon-line-clipboard i-circled i-small"></a> <a href="#" class="icon-file-alt2 i-circled i-small"></a>';
}
你知道為什么嗎 ?
函數中的整個代碼是
$('#recevabilite').dataTable({
"scrollY": "200px",
"scrollCollapse": true,
"paging": false,
stateSave: true,
"dom": '<"#recev.top">irt',
"columnDefs": [{
"visible": false,
"targets": [3]
},
{
"render": function(data, type, row) {
// var date1 = new Date()+10J;
//affichage des icones
var x = localStorage.getItem("listeFavoris");
xt = x.split(',');
for (var h = 0; h < xt.length; h++) {
var heart = '';
console.log(xt[h]);
if (row[0] == xt[h]) {
heart = 'icon-heart';
} else {
heart = 'icon-heart1';
}
return '<i class="' + heart + '" onClick="addFAv(this)" data-id="' + row[0] + '" data-name="' + row[1] + '"></i> <a href="#" class="icon-line-clipboard i-circled i-small"></a> <a href="#" class="icon-file-alt2 i-circled i-small"></a>';
}
謝謝
當您執行return
,它會結束該函數,因此您不會執行循環的任何進一步迭代。
您需要連接每個循環迭代的值,然后在循環后返回最終結果:
"render": function(data, type, row) {
// var date1 = new Date()+10J;
//affichage des icones
var x = localStorage.getItem("listeFavoris");
var xt = x.split(',');
var html = '';
for (var h = 0; h < xt.length; h++) {
var heart = '';
console.log(xt[h]);
if (row[0] == xt[h]) {
heart = 'icon-heart';
} else {
heart = 'icon-heart1';
}
html += '<i class="' + heart + '" onClick="addFAv(this)" data-id="' + row[0] + '" data-name="' + row[1] + '"></i> <a href="#" class="icon-line-clipboard i-circled i-small"></a> <a href="#" class="icon-file-alt2 i-circled i-small"></a>';
}
return html;
}
我找到了解決方案
{"render": function(data, type, row) {
// var date1 = new Date()+10J;
//affichage des icones
var x = localStorage.getItem("listeFavoris");
var xt = x.split(',');
var html = '<a href="#" class="icon-line-clipboard i-circled i-small"></a> <a href="#" class="icon-file-alt2 i-circled i-small"></a>';
for (var h = 0; h < xt.length; h++) {
var heart = '';
console.log(xt[h]);
if (row[0] == xt[h]) {
heart = 'icon-heart';
h = xt.length; }
html += '<i class="' + heart + '" onClick="addFAv(this)" data-id="' + row[0] + '" data-name="' + row[1] + '"></i>';
}
if (heart == '') {
html += '<i class="icon-heart1" onClick="addFAv(this)" data-id="' + row[0] + '" data-name="' + row[1] + '"></i>';}
return html;
}, "targets": 4}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.