2010-01-09 44 views
1

我有一張表,我想在下一行的td中插入html。 我粘貼在下面一行。jquery插入html不起作用

<tr class="content"> 
    <td align="center"> 
     <a class="version" href="theurl">click here to update the td in the row below</a> 
    </td> 
    <td align="left">col 2</td> 
    <td align="left">col 3</td> 
    <td align="left">col 4</td> 
    <td align="left">col 5</td> 
    <td align="left">col 6</td> 
</tr> 
<tr class="version" style="display: none;"> 
    <td colspan="6"></td> <-- this is where i want to insert the new html in. 
</tr> 

我的jQuery腳本看起來像這樣。

$("a.version").click(function() { 
    var sLink = $(this).attr("href"); <-- this gets the link to retrieve data from 
    var nexttr = $(this).parent().parent().next(".version"); <-- gets the next tr 
    var nexttrtd = $(this).parent().parent().next(".version td:first"); <-- gets the first td in the next tr. alerting the colspan displays 6 (which is correct) 

    nexttrtd.html("hello world"); <-- this wont insert the text in the td. 
    nexttr.css("display", ""); 

    return false; 
}); 

現在的問題是,爲什麼HTML不顯示在TD?我試過append,innerHTML =「bla」,那也行不通。

認爲我正在按照手冊做事,但無法真正弄清楚它出錯的地方。

有什麼想法?

回答

2

next()可能失敗,因爲它試圖找到當前tr旁邊的td:first元素。試試這個:

$("a.version").click(function() { 
    var sLink = $(this).attr("href"); <-- this gets the link to retrieve data from 

    var nexttrtd = $(this).closest('tr').next('.version').find('td:first'); 
    nexttrtd.html("hello world"); // This will insert "hello world" to the td 

    return false; 
}); 

我減少了一些似乎沒有做任何事的冗餘代碼。奇怪的是,你選擇了nexttr,但隨後從頭開始重新搜索nexttrtd。你可以剛剛使用nexttr元素來幫助:

var nexttr = $(this).closest('tr').next(".version"); // gets the next tr 
var nexttrtd = nexttr.find('td:first'); // Gets the first td in that row 
+0

別忘了'nexttr.show();'「hello world」後放入td – munch 2010-01-09 18:11:50

+0

謝謝!我放入了冗餘代碼以確保我獲得了正確的元素。但是使用.find鏈接nexttr可以完成所有工作。 它也解決了我寫的第二個問題(。html) – 2010-01-09 18:49:00

+0

@半個書呆子,如果它解決了你的問題,不要忘記標記答案爲接受:) – 2010-01-09 19:21:16

0

我試過你的代碼,它適用於我。 jQuery是否正確包含在您的頁面標題中,沒有任何錯字?我測試了它

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
0

確保您的jQuery腳本在頁面上執行。如果不是,則單擊事件將永遠不會添加到您的標記中。

0

現在有一部分工作。在下一個tr中獲得td的關鍵是:

var nexttrtd = $(this).parent()。parent()。next(「tr.version,td」); $ .get(sLink,function(sData){「+ sData +」「); nexttr.css(」display「,」「); });

(在「tr.version,td」中的逗號)現在的事情是,html不會插入sData字符串IN但是IN STEAD。

這就是爲什麼我繞到通過插入「太多,但肯定這是沒有辦法的辦法應該還是什麼?

有沒有做到這一點有道?

(追加SDATA會但SDATA旁邊,這樣也不會被通緝。

2

HTML不插入SDATA字符串中的,但STEAD的。

使用.append(),而不是.html()!

+0

yepp工作,但只有在我將它追加到與nexttr.find(「td :第一個「),在使用append時代碼會插入​​旁邊。 感謝您的幫助。 – 2010-01-09 18:50:35

+0

對於看到這個的未來用戶,如果需要重置,append將僅向對象添加新信息,而不是使用html(); – 2017-09-13 18:55:29