简体   繁体   English

替换内容 <td> 与 <tr> id和 <tr> 指数

[英]Replacing the content of a <td> with <tr> id and <tr> index

I have a table structure like this 我有这样的表结构

<table>
    <tr id="tr_1">
        <td>Content1</td>
        <td>Content2</td>
        <td>Content3</td>
        <td>Content4</td>
    </tr>
    <tr id="tr_2">
        <td>Content5</td>
        <td>Content6</td>
        <td>Content7</td>
        <td>Content8</td>
    </tr>
    <tr id="tr_1">
        <td>Content11</td>
        <td>Content12</td>
        <td>Content13</td>
        <td>Content14</td>
    </tr>
    <tr id="tr_2">
        <td>Content15</td>
        <td>Content16</td>
        <td>Content17</td>
        <td>Content18</td>
    </tr>
</table>

I am passing the row index(2) and <tr> id (tr_1) to a js function for replacing the content of 2nd 3 rd td's in that row. 我将行index(2)和<tr> id(tr_1)传递给js函数,以替换该行中第二个第3个td的内容。 i have a jquery funcion 我有一个jQuery函数

document.getElementById('tr_1').getElementsByTagName("td")[2].innerHTML = '<td>New html</td>';

But that this replacing the first tr html. 但是,这取代了第一个tr html。 How we can replace with id tr_1 with index 2 如何使用索引为2的id tr_1替换

Try this: 尝试这个:

jQuery("[id=tr_1]:eq(1) td:eq(1)").html("new html");

Note you need to insert the jquery plugin: 注意,您需要插入jquery插件:

http://jquery.com/download/ http://jquery.com/download/

if you are using jquery .. then this should work.. 如果您使用的是jQuery ..那么这应该工作..

$("#tr_1 td").eq(2).html("<td>New html</td>");

here is the link to eq()... http://api.jquery.com/eq/ 这是eq()的链接... http://api.jquery.com/eq/

Try this 尝试这个

<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
    $('#tr_1 td:eq(1)').html('Replacing Content of td 2');
    $('#tr_1 td:eq(2)').html('Replacing Content of td 3');
});                
</script>

You don't have unique ids. 您没有唯一的ID。 Is is essential for JavaScript that the DOM working with unique ids. 对于DOM使用唯一ID的JavaScript是必不可少的。

In jQuery you can use this to target the to tr elements with id set to tr_1 : 在jQuery中,您可以使用此方法将id设置为tr_1的to tr元素作为目标:

$("tr[id=tr_1]");

To get the second element in these tr's you will need to use jQuery.fn.each 要获得这些tr中的第二个元素,您将需要使用jQuery.fn.each

$("tr[id=tr_1]").each(function() {
    $("td", this).eq(1).html("new html");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM