2011-08-03 39 views
3

我試圖在JavaScript函數中替換td標記的內容,但無法弄清楚發生了什麼。這是功能。使用javascript/jquery設置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控件的問題,所以我添加了空檢查。

然後我認爲這是.text(),所以我試着.html()。

我想也許它是吞嚥異常,所以我添加了try..catch。

然後我認爲這可能是一個接收函數的響應對象的問題,所以我在那裏扔了一些警報,他們有我需要的值。

我檢查了ID並確保它們與在頁面的html中找到的ID匹配。

我檢查了我能想到的一切。但我的代碼根本無法工作。我試圖設置的兩個TD元素中的第一個包含兩個鏈接(一個標籤),但第二個是空的。所以我認爲這與它沒有任何關係。試圖弄清楚這一點,我就在這裏結束了。

有什麼我做錯了嗎?會不會有別的東西會導致這種行爲?

在此先感謝。

+0

你可以添加(的相關部分)的HTML? – dvdvorle

+1

因此var tdstatus和tdreason正在工作? – Pehmolelu

回答

4

由於jQuery調用總是返回一個jQuery對象,它們永遠不會爲空。要測試包裝集是否爲空,您可以檢查長度。

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

此外,我不確定什麼是調用此函數,但如果它被用作AJAX回調,它的簽名實際上是f(data, textStatus, jqXHR)

+0

這有幫助。我的表格ID不正確。我曾假設,因爲我的單元格對象不是空的,並且表格行上的查找沒有拋出異常,那麼該行是OK的。事實證明,事實並非如此。 –

+0

好聽。順便說一下,如果你選擇了這樣一行:'$('#tdreasonId-'+ response.id,'#itemDetails')'而不是選擇3個元素,那麼效率會更高。 –

+0

我沒有意識到這種語法。但是,這不是跳過行查找? $('#tdreasonId-'+ response.id,'#itemDetails')中的第二個參數是表的ID。行ID不需要? –

1

我有幾分相似,你的情況在工作的jsfiddle東西:

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

也許你可以修改,使用您的代碼,並得到它的失敗。我們可以從那裏開始。儘量保持簡單並儘可能地解決問題,這樣會更容易。