简体   繁体   English

获取连续表格单元格的值(JS 或 jQuery)

[英]Get the value of table cell in a row (JS or jQuery)

I have a table that incorporates 50 identical我有一张桌子,其中包含 50 个相同的

<tr>
    <td>#</td>
    <td>#</td>
    <td>123123</td>
</tr>
...

and now I am able to get the value of a specific row like this现在我可以像这样获取特定行的值

$("#tableId tbody tr").each(function(){
    var a = $(this).children();
    var arr =a[2].innerText; //get each row
    a[2].innerText = statename // get the third cell in each row
});

In this case, statename is an object with 50 states names.在这种情况下, statename是一个具有 50 个状态名称的对象。 All I want to do now is to substitute that 123123 to each state name inside the object.我现在要做的就是将123123替换为对象内的每个状态名称。 So that it looks like this:所以它看起来像这样:

<tr>
    <td>#</td>
    <td>#</td>
    <td>Alabama</td>
</tr>
<tr>
    <td>#</td>
    <td>#</td>
    <td>Alaska</td>
</tr>
<tr>
    <td>#</td>
    <td>#</td>
    <td>Arizona</td>
</tr>
...

I tried to loop within the jQuery but it did not work.我试图在 jQuery 中循环,但没有奏效。 Please help, thank you very much.请帮忙,非常感谢。

You can try to use each method with find method, in the selector name, you can search the last <td> element by td:last .您可以尝试将each方法与find方法一起使用,在选择器名称中,您可以通过td:last搜索最后一个<td>元素。 Like this:像这样:

 var statenames = ['Alabama', 'Alaska', 'Arizona']; $("#tableId tbody tr").each(function(index){ $(this).find('td:last').text(statenames[index]); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="tableId"> <tbody> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> </tbody> </table>

By using vanilla js, you can easily get the last td elements in tr, loop through them and assign new values to the nodes通过使用 vanilla js,您可以轻松获取 tr 中的最后一个 td 元素,遍历它们并为节点分配新值

 const stateNames = ['Alabama', 'Alaska', 'Arizona']; document.querySelectorAll('tr td:last-child') .forEach((x, i) => x.textContent = stateNames[i])
 <table> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> </table>

Make sure your variable statename is an array, and don't forget the index of the state确保您的变量statename是一个数组,并且不要忘记状态的索引

// find elements
statename = ["Alabama", "Alaska", "Arizona"]
$("#tableId tbody tr").each(function(index){
    var a = $(this).children();
    var arr =a[2].innerText; //get each row
    a[2].innerText = statename[index] // get the third cell in each row
});

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

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