开发者

Cannot retrieve values from JS object using hash syntax

开发者 https://www.devze.com 2023-01-29 08:12 出处:网络
I\'m seeing strange behavior when accessing properties from a JS object via the [] operator. I have 3 columns in a table \'attr1\', \'attr2\', \'attr3\'. My JS object has a property called Attributes

I'm seeing strange behavior when accessing properties from a JS object via the [] operator.

I have 3 columns in a table 'attr1', 'attr2', 'attr3'. My JS object has a property called Attributes, which is a hashtable that looks like {attr1: 'val', attr2:开发者_如何学编程 'val', attr3: 'val'}

The following contrived code works fine

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;
        }
    }
}

However, the following code, where I'm dynamically building the keys object; attribute is always undefined.

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;
        }
    }
}


Try a trim of the value:

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

Do you know what exactly keyVal contains at each iteration?


Try this...

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

Does that get you what you want?

0

精彩评论

暂无评论...
验证码 换一张
取 消