繁体   English   中英

如何遍历表tr并获取第一个td的值? 的JavaScript

[英]How to iterate through table tr and get the value for first td? JavaScript

我有要获取每个表行中第一个td值的函数。 循环时,我想将每个值与用户选择的日期值进行比较。 比较日期之后,我需要获取该值应在表格中放置的位置。 这是我的代码示例:

HTML表格:

<table id="tblBody_DBA">
    <tbody>
        <tr id="Att_5258717">
            <td>03/28/2017</td>
            <td></td>
        </tr>
        <tr id="Att_5258339">
            <td>03/25/2017</td>
            <td>03/26/2017</td>
        </tr>                       
        <tr id="Att_5258337">
            <td>03/22/2017</td>
            <td>03/24/2017</td>
        </tr>
        <tr id="Att_5258332">
            <td>03/16/2017</td>
            <td>03/21/2017</td>
        </tr>
        <tr id="Att_5258331">
            <td>03/10/2017</td>
            <td>03/15/2017</td>
        </tr>
    </tbody>
</table>

 function sortRow(distType, rowId){
        var newVal = document.getElementById("newDate").value; //this is new value that I have to compare against existing values and return position in the table.
        var tblID = document.getElementById("parentTable").value;
        var table = window.parent.document.getElementById("tblBody_"+tblID);
        var arrayDates = [];

        for(var i=0; table.rows.length; i++){
            //Here I'm getting JavaScript error: TypeError: table.rows[i] is undefined
            alert(table.rows[i].cells[0].innerHTML);
        }

    }

我在警报框中获取每个表单元的值,但最后在调试器中显示错误。 如果有人可以帮忙,请告诉我。 我无法使用JQuery,在我的情况下,纯JavaScript是完成此操作的唯一方法。

您可以只从每个tr抓取第一个td

var table = document.getElementById('tblBody_DBA');
var targetTDs = table.querySelectorAll('tr > td:first-child');


for (var i = 0; i < targetTDs.length; i++) {
    var td = targetTDs[i];
    console.log(td.innerHTML);
}

首先,使用var allTr = document.querySelectorAll ('tr')获得所有tr元素

然后遍历它们并从第一个td获取文本

for (var i = 0; i  < allTr.length; i++) {
  allTr [i].firstChild.innerHTML;
}

主要问题在于for循环的结束条件。 您没有提供与i的比较,因此它继续超出表的最后一行,从而产生错误。

要查找输入日期介于第一列和第二列中的日期之间的行,您需要将这些值转换为日期,然后进行比较:

// Parse text as date and convert to an absolute day number 
newVal = Math.floor(Date.parse(newVal) / 24*60*60*1000);
for(var i=0; i < table.rows.length; i++){
    // Do the same conversion for the table texts
    var start = Math.floor(Date.parse(table.rows[i].cells[0].textContent) / 24*60*60*1000);
    var end = Math.floor(Date.parse(table.rows[i].cells[1].textContent) / 24*60*60*1000);
    // Make the comparison
    if (start <= newVal && (newVal <= end || isNaN(end))) {
        return i; // the row where the range for that value was found
    }
}

 <table id="tblBody_DBA"> <tbody> <tr id="Att_5258717"> <td>03/28/2017</td> <td></td> </tr> <tr id="Att_5258339"> <td>03/25/2017</td> <td>03/26/2017</td> </tr> <tr id="Att_5258337"> <td>03/22/2017</td> <td>03/24/2017</td> </tr> <tr id="Att_5258332"> <td>03/16/2017</td> <td>03/21/2017</td> </tr> <tr id="Att_5258331"> <td>03/10/2017</td> <td>03/15/2017</td> </tr> </tbody> </table> <script> function sortRow(distType){ var table = document.getElementById(distType); //this is new value that I have to compare against existing values and return position in the table. for (var i = 0; i < table.rows.length; i++) { var firstCol = table.rows[i].cells[0]; //first column console.log(firstCol.innerHTML);// or anything you want to do with first col } } sortRow("tblBody_DBA"); </script>​ 

错误的可能原因可能是:

  1. document.getElementById(“ parentTable”)。value将返回在window.parent.document.getElementById(“ tblBody _” + tblID)中使用时不会映射到任何表ID的值
  2. 表格中没有window.parent.document.getElementById(“ tblBody _” + tblID)返回的行;
  3. 另外,您还没有在for循环中提供终止条件,该条件应类似于: for(var i=0; i < table.rows.length; i++)

为什么要在获取表时使用window.parent的另一件事。 如果您的表和其余内容在同一页面中,则只需调用document.getElementById(“ tblBody _” + tblID);即可获取表 如果创建多帧页面,则将需要此页面,但这将从定义了sortRow函数的窗口的父窗口获取表格。

忘记粘贴此代码段,可能会有所帮助。 除非您回答评论中的问题,否则无法确定最佳方法。

注意:以下代码使用某些ES6语法,如@Brian所指出的那样,在IE中可能不可用。 因此,鼓励使用Babel.js或合适的Polyfill。


想法是获取每行的第一个子单元并对其进行迭代。 使用map可以返回一个数组,然后可以使用indexOf对其进行排序或查询。

通过将元素作为数组的第一项返回,可以使用[0].parentNode来检索TR,或使用[0].parentNode.id来获取其ID。

 "use strict"; let newVal = document.getElementById('newDate').value; console.log('newVal:', new Date(newVal)); let tbl = document.getElementById('tblBody_DBA'); var col_values = [...tbl.querySelectorAll('tr > td:first-child')].map(el => { return [el, el.textContent, +new Date(el.textContent)]; }).sort((a,b) => a[2] > b[2] ? -1 : 1); console.log(col_values); 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <p>I have the function where I want to get the value for first td in each table row. While looping I want to compare each of these values with the date value that user picked. After comparing the dates I need to get the position where that value should be placed in the table. Here is example of my code:</p> <p>HTML Table:</p> <input id="newDate" value='3/24/2017' type="hidden" /> <table id="tblBody_DBA" class="table table-striped"> <tbody> <tr id="Att_5258717"> <td>03/28/2017</td> <td></td> </tr> <tr id="Att_5258339"> <td>03/25/2017</td> <td>03/26/2017</td> </tr> <tr id="Att_5258337"> <td>03/22/2017</td> <td>03/24/2017</td> </tr> <tr id="Att_5258332"> <td>03/16/2017</td> <td>03/21/2017</td> </tr> <tr id="Att_5258331"> <td>03/10/2017</td> <td>03/15/2017</td> </tr> </tbody> </table> <p> I'm getting value for each table cell in alert box but on the end error shows in my debugger. If anyone can help please let me know. I'm not able to use JQuery, plain JavaScript is the only way to et this done in my case.</p> 

暂无
暂无

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

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