2010-07-07 53 views
0

我有一個包含有這樣的虛擬數據表中的基本DOM「綱目」:更換DOM文本與jQuery

<table> 
    <tr> 
    <td>name</td> 
    <td>phone</td> 
    </tr> 
</table> 

我的腳本使用這個作爲一個虛擬的行克隆和更換TD之間的文本標籤與數據庫中的文本。如果不在這裏複製整個腳本,以下是我嘗試過的兩種不同的東西:

newRow.find("td.name").text(participant.name); 

newRow.find("contains("phone")").text(participant.homePhone); 

兩者都不起作用。腳本克隆並顯示行很好,但我有30行「名稱」和「電話」。

我使用Firebug的console.log進行調試,我確信它從JSON中獲取了正確的數據,並加載到「參與者」參數中。我究竟做錯了什麼?

+1

真的需要看到腳本/標記 – redsquare 2010-07-07 19:22:25

回答

1

第二個版本幾乎是正確的,如果我明白你要做什麼。請注意選擇器前面的冒號和內部單引號的用法。

newRow.find(":contains('name')").text(participant.name); 
newRow.find(":contains('phone')").text(participant.homePhone); 

更好的是給模板類和使用這些或簡單地依靠定位。

定位:

newRow.find('td:first-child') 
     .text(participant.name) 
     .next() 
     .text(participant.homePhone); 

類:

newRow.find('td.name').text(participant.name); 
newRow.find('td.phone').text(participant.homePhone); 

迫使這一變化:

<table> 
    <tr> 
    <td class="name">name</td> 
    <td class="phone">phone</td> 
    </tr> 
</table> 
+0

謝謝。我選擇了這個答案作爲答案,但幾乎每個人都告訴我要使用類。當然!現在正在工作。 – 2010-07-09 16:40:07

+0

@Carrie - 請注意,類是一個很好的方法來做到這一點。例如,如果某人的名字包含字符串「phone」,那麼我不會使用'contains'方法,因爲您可能會遇到問題。 DOM相關機制運行良好,但對錶結構中的更改很敏感。 – tvanfosson 2010-07-09 16:45:50

6

您使用的是td.name,它不存在於您的標記中。 .name表示一個類,所以你需要像這樣的標記:<td class="name"></td>爲了工作。

如果你使用這個作爲一個虛擬行和更換這兩個TD的,我會提供類給每個喜歡<td class="name"></td><td class="phone"></td>使用newRow.find("td.name")或使用類似:newRow.find("td:first")newRow.find("td:last")

0

find('td.name')尋找一個tdclass="name",你沒有。我建議添加這個到你的HTML來創建一個jQuery更新文本的鉤子。特別是如果你在頁面上有幾個。

另外,你怎麼設置newRow

2
newRow.find("td:contains(name)").text(participant.name); 

newRow.find("td:contains(phone)").text(participant.homePhone); 
+0

現在的休息,會發生什麼,如果參與者的名字是Stephone Andrews? – 2010-07-07 19:36:07

+0

呵呵。我同意使用classnames更有意義,但我試圖糾正他提供的邏輯,而不是將他重定向到更好的解決方案... – 2010-07-07 19:41:27

+0

@Gert G - 你說得對。我沒在想。 – tvanfosson 2010-07-07 20:31:16