使用jquery将html添加到表中

时间:2014-05-21 11:44:24

标签: javascript jquery html

我有这样的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更改此内容。

6 个答案:

答案 0 :(得分:2)

这是一个班轮:

   $('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

答案 1 :(得分:1)

例如,所以:

$('td', 'table').first().text('hello!');

答案 2 :(得分:1)

您可以在下次尝试谷歌搜索。

jquery方法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

答案 3 :(得分:0)

在代码看起来像

的情况下为第一个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>

答案 4 :(得分:0)

如果你给你的表一个id有帮助,那么你可以做类似的事情:

$('#id >tbody').prepend('<tr><td>A shiny new row<td></tr>');

答案 5 :(得分:0)

如果您根本无法访问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);

我做了一个例子here

基本上它是关于使用正确的JQuery选择器,因此$(table:nth-of-type(2)将选择第二个表。然后你可以使用我上面的代码,或者甚至更好,但这里是一个单行:

$("table:nth-of-type(2) tbody tr").first().before("<tr><td>Your New Text Here</td></tr>");