简体   繁体   中英

Cannot retrieve values from JS object using hash syntax

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM