2010-01-09 38 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