【问题标题】:how to select all first td's inside all <tr> in to an array如何选择所有<tr>中的所有第一个td到一个数组中
【发布时间】:2025-12-31 12:00:07
【问题描述】:

我需要先将所有行 td 放入一个 javascript 数组中,然后检查数组中是否存在元素打印一些东西。

我能知道如何使用 jquery 或 javascript 来完成吗?

我在这里创建了一个提琴手。 http://jsfiddle.net/RXD2u/1/

<table id="tbl_dynamic_call_dates" border="1">
    <tr>
        <td>07/10/2013</td>
        <td>Cell B</td>
    </tr>
    <tr>
        <td>08/10/2013</td>
        <td>Cell B</td>
    </tr>
    <tr>
        <td>09/10/2013</td>
        <td>Cell B</td>
    </tr>
    <tr>
        <td>Cell A</td>
        <td>Cell B</td>
    </tr>
</table>

EDIT 1我应该省略第一行并获取所有其他行。我尝试了下面给出的 asnwer,但它没有省略第一行。

var arr = $('#tbl_dynamic_call_dates tr td:first-child').map(function () {
    return $.trim($(this).text())
}).get();

【问题讨论】:

  • 您是否尝试过自己解决这个问题?请您提供您已经尝试过的任何代码吗?

标签: javascript php jquery html arrays


【解决方案1】:

试试

var arr = $('#tbl_dynamic_call_dates tr:gt(0) td:first-child').map(function () {
    return $.trim($(this).text())
}).get();

console.log(arr)

然后使用$.inArray()进行测试

喜欢

var exists = ( $.inArray('08/10/2013', arr) != -1 );

演示:Fiddle

【讨论】:

  • 向大师低头!!!在 2 分钟内,您给出了一个完整的解决方案,只涉及 2 行代码。
  • @Arun P tnx 很多。但我需要跳过第一行并获得所有其他人。这是因为我在工作中定义了一个表头,需要跳过它。我现在在数组中得到的是 ["Appointment date", "07/10/2013", "08/10/2013", "10/10/2013", "11/10/2013"]
  • Mazraara,我认为在这种情况下不需要对此代码进行任何更改,因为标头是一个字符串,并且与您要交叉检查的日期不匹配
  • @Arun 这会返回 true 还是 false ? var 存在 = ( $.inArray('08/10/2013', arr) != -1 );我问天气你检查是否存在或不存在?
  • @ArunPJohny 你能回答这个问题吗*.com/questions/19178488/…
【解决方案2】:

试试 -

$("table tr :first-child")

【讨论】:

    【解决方案3】:

    使用 JQuery,这应该可以工作

    $("tr td:first-child")
    

    这将为您提供您的第一个 td,然后您可以随心所欲地使用它们

    【讨论】:

      【解决方案4】:

      使用下面的jQuery代码:

      $(document).ready(function(){
        $("table tr").each(function(index,value){
           var val = $(this).find("td:first").text();
           alert(val);
        });
      });
      

      还包括 jQuery 库。

      【讨论】:

        【解决方案5】:

        试试这个。

        $("table tr td:first-child").each(function(index,value){
             var val = $(this).text();
             alert(val);
        });
        

        DEMO

        【讨论】:

        • 你需要包含 jquery。
        最近更新 更多