2010-12-08 31 views
1

當通過[]運算符訪問JS對象的屬性時,我看到奇怪的行爲。無法使用哈希語法從JS對象檢索值

我在表格中有3列'attr1','attr2','attr3'。我的JS對象有一個名爲屬性屬性,這是一個哈希表,看起來像{attR1位: 'VAL',attR2位: 'VAL',attr3: 'VAL'}

以下做作代碼工作正常

function onRowDataBound(e) { 
    var attributes = e.dataItem.Attributes; 
    var keys = {0: 'attr1', 1: 'attr2', 2: 'attr3'}; 
    for (var key in keys) { 
     var keyVal = keys[key]; 
     var attribute = attributes[keyVal]; 
     if (attribute != undefined) { 
      e.row.cells[key].innerText = attribute; 
     } 
    } 
} 

但是,下面的代碼中,我動態地構建了鍵對象; 屬性始終未定義。

function getKeys() { 
    var keys = {}; 
    $('#Equipment thead th').each(function() { 
     keys[this.cellIndex] = this.innerText; 
    }); 
    return keys; 
} 

function onRowDataBound(e) { 
    var attributes = e.dataItem.Attributes; 
    var keys = getKeys(); 
    for (var key in keys) { 
     var keyVal = keys[key]; 
     var attribute = attributes[keyVal]; 
     if (attribute != undefined) { 
      e.row.cells[key].innerText = attribute; 
     } 
    } 
} 
+1

`this.innerText`是一隻危險的猴子。 – palswim 2010-12-08 23:32:52

+0

既然你使用的是jQuery,使用`.text()`而不是`innerText` – 2010-12-09 00:03:22

回答

1

嘗試值的微調:

$('#Equipment thead th').each(function() { 
    keys[this.cellIndex] = jQuery.trim(this.innerText); 
}); 

你知道究竟是什麼keyVal包含在每次迭代?

0

嘗試......

var keys = {}; 
$("#Equipment thead th").each(function (i, e) { 
    keys[i] = $(this).html(); 
}); 

不會得到你想要的是什麼?