[英]Adding html to a table using jquery
我有这样的html表:
<table cellpadding="2" cellspacing="1" width="700">
<tbody>
<tr>
<td class="dark" colspan="2">
Customer Details
</td>
</tr>
<tr>
<td>
Customer Contact Name
</td>
<td>
<input name="tbname" type="text" id="tbname" class="widetb">
</td>
</tr>
</tbody>
</table>
我想在表的开头添加一些文本,因此这是表中的第一个td,如何使用jquery做到这一点? 我真的不知道从哪里开始。
我必须这样做,因为我无权通过html进行更改。
这是一个班轮:
$('td.dark').text('Enter your text here!'); // the class is present in your HTML
这将搜索td
与类dark
它代表了第一个TD,它会插入文本。
如果您有多个表:
$('td.dark').eq(0).text('Enter your text here!');
// here 0 represents the position of the table minus 1 , you want to change the text
例如:
$('td', 'table').first().text('hello!');
您下次可以尝试使用Google搜索。
jQuery方法find
在与选择器匹配的父级中find
元素集,然后eq
从集合中选择某个元素(元素1被数组引用为0)。 因此,如果整个文档中只有一个表,则可以使用以下命令:
$("table") // select all tables
.eq(0) // select the one you want (the only one)
.find("td") // select all td's
.eq(0) // select the first one (the one you want)
.html("insert new content here"); // set the td's inner html
如果您有多个表,这很棘手。 您将需要表相对于其他表的索引。 例如,如果您有
<table>...</table>
...
<table>...</table>
...
<table>table you are targeting</table>
.......
然后,表的索引将为2
因为它是文档中的第三个表,索引从0开始。如果有索引,则可以使用
var table_index=// set this to the index
$("table") // select all tables
.eq(table_index) // select the one you want (with the index)
.find("td") // select all td's
.eq(0) // select the first one (the one you want)
.html("insert new content here"); // set the td's inner html
给您的First td输入ID,因为您的代码如下所示
<table cellpadding="2" cellspacing="1" width="700">
<tbody>
<tr>
<td id="firsttd" class="dark" colspan="2">
Customer Details
</td>
</tr>
<tr>
<td>
Customer Contact Name
</td>
<td>
<input name="tbname" type="text" id="tbname" class="widetb">
</td>
</tr>
</tbody>
</table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$('#firsttd').text("Your title here");
</script>
如果为表提供一个ID,则可以执行以下操作:
$('#id >tbody').prepend('<tr><td>A shiny new row<td></tr>');
如果您根本无法访问HTML,并且有多个表,则可以使用:
var newTR = $( "<tr id='newRow'/>" );
var newTRcontent = "<td colspan=1>Your New Text Here</td>";
$("table:nth-of-type(2) tbody tr").first().before(newTR);
$("#newRow").html(newTRcontent);
我在这里做了一个例子
基本上,它是关于使用正确的JQuery选择器的,因此$(table:nth-of-type(2)
将选择第二个表。然后,您可以使用上面有的代码,甚至可能更好,但是这里有一个代码:
$("table:nth-of-type(2) tbody tr").first().before("<tr><td>Your New Text Here</td></tr>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.