你知道为jqgrid正确地重写“this”吗?

时间:2014-09-14 06:59:55

标签: jquery jqgrid

我有一个像这样的jqgrid:

$("#MyTable").jqGrid({
        height: 600,
        url: 'list.json',
        colNames: ColN,
        colModel: Colm,
        sortable: true,
        multiselect: true,
loadComplete: function() {

getEditPage('#MyTable');

}
});

getEditPage函数是:

function getEditPage(tableId,objectType){
    var ids = $(tableId).jqGrid('getDataIDs');
        var idList = "";
        for (var i = 0; i < ids.length; i++) {
        idList = idList + ids[i] + " ";
        }

    for (var i = 0; i < ids.length; i++) {
        $('#'+ids[i]+' a').click(function(e) {editClickEvent(e, tableId, objectType, idList);});
    }
    if ($(tableId + '_forzen')) {
            $(tableId + '_frozen tr').slice(1).each(
                    function() {
                        $('td', this).each(
                                function() {
                                    $('a', this).click(function(e) {editClickEvent(e, tableId, objectType, idList);});
                                }
                        );
                    });
       }
};

这是editClickEvent:

var editClickEvent = function(e, tableId, objectType, idList) {
    $(window).unbind("beforeunload");
    var myHash = e.currentTarget.hash;     // string like "#?id=0"
    var id = myHash.substring(5, myHash.length); // getting row Id
    if (id.indexOf("&") >=0) {
        id = id.substring(0, id.indexOf("&"));
    }
    if (myHash.substring(0,5) === '#?id=') {
        var rowData = $(tableId).jqGrid('getRowData', id);
        var param = myHash.substring(myHash.length-1);
        if (objectType) {
            param = objectType;
        }
        if(param == 'D'){
            var cellValue = this.textContent || this.innerText;
            if((cellValue.search('\n') != 0)&&(cellValue.lastIndexOf('\n')==cellValue.indexOf('\n')))        {
                var m_Id = rowData.id;
                var m_Id = m_Id.substring(0,m_Id.length-1);
                var url = 'path';
                hasPermissionByIds('M', m_Id, 1, gotoPage, url);
            } else if(cellValue.search('\n') != 0){
                var cellValueArray = makeArray2(cellValue);
                var cellIdsArray = makeArray2(rowData.id);
                createPromtDialog(cellValueArray, cellIdsArray, param);                                 
            }
e.preventDefault();
};

问题出在var cellValue = this.textContent || this.innerText;。 textContent和innerText未定义。我知道这是&#34;这个&#34;引用错误。你知道我可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您应该更改函数editClickEventgetEditPage的调用,以便转发this的值(请参阅herehere)。例如

$('#'+ids[i]+' a').click(function(e) {editClickEvent.call(this, e, ...

而不是

$('#'+ids[i]+' a').click(function(e) {editClickEvent(e, 

getEditPage.call(this, '#MyTable');

而不是

getEditPage('#MyTable');

顺便使用.call后,您可以修改getEditPage的代码,以便从id获取该表的tableId值:this.id将是"MyTable"。因此"#" + this.id等于"#MyTable"