我有一个表,我想在下一行的 td 中插入 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 中?我已经尝试过追加,innerHTML =“bla”,但这也不起作用。
我认为我正在按照手册做事,但无法真正弄清楚哪里出了问题。
有什么想法吗?
最佳答案
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
关于jquery插入html不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2034244/