2014-04-11 39 views
0
function initGrids() { 
    for (var i = 0; i < grids.length; i++) { 

     $('#' + grids[i].gridName).kendoGrid({ 
      columns: [{ 
       width: 50, "template": "<input type=\"checkbox\" />" 
      }, 
      { 
       field: "Name", 
       title: "Name" 
      }], 
      dataBound: function() { 
       noRecords(grids[i].gridName); 
      } 
     }).css('width', '100%'); 
    } 
} 

我有這個函數可以初始化多個kendo ui網格。網格具有可隨時調用的函數,如databound和transport.read。loop中的函數在循環完成後調用

這意味着在for循環完成後調用像dataBound這樣的函數。這也意味着增量變量var i;將在grids.length + 1,所以,當數據綁定函數被調用,它包含這段代碼noRecords(grids[i].gridName),柵格[I]將是錯誤的索引處!

一個解決方法是手動定義網格一個接一個,但我有一個具有完全相同的列等,但隨後的代碼會看起來很糟糕,因爲我重複的東西三個光柵。

我該如何解決這個問題?

回答

1

使用一個單獨的功能或使用閉合

封閉

for (var i = 0; i < grids.length; i++) { 
    (function(index){ 
     $('#' + grids[index].gridName).kendoGrid({ 
      columns: [{ 
       width: 50, "template": "<input type=\"checkbox\" />" 
      }, 
      { 
       field: "Name", 
       title: "Name" 
      }], 
      dataBound: function() { 
       noRecords(grids[index].gridName); 
      } 
     }).css('width', '100%'); 
    })(i); 
} 

或功能

function initGrid(grid){ 
    $('#' + grid.gridName).kendoGrid({ 
     columns: [{ 
      width: 50, "template": "<input type=\"checkbox\" />" 
     }, 
     { 
      field: "Name", 
      title: "Name" 
     }], 
     dataBound: function() { 
      noRecords(grid.gridName); 
     } 
    }).css('width', '100%'); 
} 

for (var i = 0; i < grids.length; i++) { 
    initGrid(grids[i]); 
} 
+0

謝謝,夥計。它似乎工作。第二種方法對我來說很棒,因爲我不太瞭解封閉。我要去做一些關於他們的研究,因爲我認爲他們不能派上用場! – user1534664

1

你必須使用一個closure這裏捕捉到我與它的循環特定值

// ... 
dataBound: (function (index) { 
    return function(){ 
     noRecords(grids[index].gridName); 
    } 
})(i) 
// ... 
+0

感謝您的鏈接。 – user1534664