使用javascript / jquery设置TD内容

时间:2011-08-03 19:10:38

标签: javascript jquery

我正在尝试在javascript函数中替换td标记的内容,但无法弄清楚发生了什么。这是功能。

function actionCompleted(response, status, data) {

    // Set the id for row
    var rowId = "#rowId-" + response.fieldname;

    // Set the ids for the two table cells we need
    var tdstatusId = "#tdstatusId-" + response.id;
    var tdreasonId = "#tdreasonId-" + response.id;
    alert(tdreasonId);

    try {
        //get the table cell for the status
        var tdstatus = $('#itemDetails').find(rowId).find(tdstatusId);
        //get the table cell for the reason
        var tdreason = $('#itemDetails').find(rowId).find(tdreasonId);

        //Make sure we found our cells
        if (tdstatus != null && tdreason != null) {
            //Set our cell content
            //tdstatus.html(response.ChangeStatus);
            //tdreason.text(response.message); 
            tdstatus.html('TEST');
            tdreason.text('TEST'); 
        }
    }
    catch (e) {
        alert(e.toString());
    }
}

我首先想到jquery找到td控件可能有问题,所以我添加了null检查。

然后我认为它是.text()所以我试过.html()。

我想也许是吞下一个例外,所以我添加了try..catch。

然后我认为这可能是函数收到的响应对象的问题,所以我在那里发出了一些警告,它们具有我需要的值。

我检查了ID并确保它们匹配了页面html中找到的id。

我已经检查了我能想到的一切。但我的代码根本不起作用。我试图设置的两个TD元素中的第一个包含两个链接(一个标签),但第二个是空的。所以我认为这与它无关。我在这里试图解决这个问题。

我有什么问题吗?可能还有其他会导致这种行为的事情吗?

提前致谢。

2 个答案:

答案 0 :(得分:4)

由于jQuery调用总是返回一个jQuery对象,因此它们永远不会为null。要测试包裹的集合是否为空,您可以检查长度。

即。 if (tdstatus.length > 0 && tdreason.length > 0)

另外,我不确定是什么调用了这个函数,但是如果它被用作AJAX回调,它的签名实际上是f(data, textStatus, jqXHR)

答案 1 :(得分:1)

我有点类似于你在jsfiddle工作的情况:

http://jsfiddle.net/jA4ZQ/1/

也许您可以使用您的代码修改它并使其失败。然后我们可以从那里开始。尽量保持简单,尽可能保持问题,这样会更容易。