简体   繁体   English

使用 JavaScript 从 HTML 表格中获取特定单元格值

[英]Get a particular cell value from HTML table using JavaScript

I want to get each cell value from an HTML table using JavaScript when pressing submit button.我想在按下提交按钮时使用 JavaScript 从 HTML 表格中获取每个单元格值。

How to get HTML table cell values?如何获取 HTML 表格单元格值?

To get the text from this cell-要从此单元格中获取文本-

<table>
    <tr id="somerow">
        <td>some text</td>            
    </tr>
</table>

You can use this -你可以用这个——

var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
    var oCells = oTable.rows.item(i).cells;
    if (modify == oCells[0].firstChild.data) {
        document.getElementById("Error").innerHTML = "  * duplicate value";
        return false;
        break;
    }

}
var table = document.getElementById("someTableID"); 
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
  {
  for (var y = 0; y <= totalCol; y++)
    {
    alert(table.rows[x].cells[y].innerHTML;
    }
  }
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note:  if you use <th> this will be row 0, so your data will start at row 1 col 0

You can get cell value with JS even when click on the cell:即使单击单元格,您也可以使用 JS 获取单元格值:

.......................

      <head>

        <title>Search students by courses/professors</title>

        <script type="text/javascript">

        function ChangeColor(tableRow, highLight)
        {
           if (highLight){
               tableRow.style.backgroundColor = '00CCCC';
           }

        else{
             tableRow.style.backgroundColor = 'white';
            }   
      }

      function DoNav(theUrl)
      {
      document.location.href = theUrl;
      }
      </script>

    </head>
    <body>

         <table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">

                <% for (Course cs : courses){ %>

                <tr onmouseover="ChangeColor(this, true);" 
                    onmouseout="ChangeColor(this, false);" 
                    onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">

                     <td name = "title" align = "center"><%= cs.getTitle() %></td>

                </tr>
               <%}%>

    ........................
    </body>

I wrote the HTML table in JSP.我在 JSP 中编写了 HTML 表。 Course is is a type.当然是一种类型。 For example Course cs, cs= object of type Course which had 2 attributes: id, title.例如Course cs, cs=Course 类型的对象,它有两个属性:id、title。 courses is an ArrayList of Course objects.课程是课程对象的ArrayList。

The HTML table displays all the courses titles in each cell. HTML 表格在每个单元格中显示所有课程标题。 So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:所以该表只有 1 列: Course1 Course2 Course3 ...... 抛开:

onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"

This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp .这意味着在用户选择表格单元格后,例如“Course2”,课程标题 - “Course2”将转到 URL 指向用户的页面: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp "Course2" will arrive in FoundS.jsp page. “Course2”将到达FoundS.jsp 页面。 The identifier of "Course2" is courseId. “Course2”的标识符是courseId。 To declare the variable courseId, in which CourseX will be kept, you put a "?"要声明将保留 CourseX 的变量 courseId,您可以输入“?” after the URL and next to it the identifier.在 URL 之后和标识符旁边。

I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine.我告诉你以防万一你想使用它,因为我搜索了很多,我发现了像我这样的问题。 But now I found out from teacher so I post where people asked.但是现在我从老师那里知道了,所以我在人们问的地方张贴。

The example is working.I've seen.这个例子是有效的。我见过。

Just simply.. #sometime when larger table we can't add the id to each tr只是简单.. #sometime 当更大的表我们不能将 id 添加到每个 tr

     <table>
        <tr>
            <td>some text</td>
            <td>something</td>
        </tr>
        <tr>
            <td>Hello</td>
            <td>Hel</td>
        </tr>
    </table>

    <script>
        var cell = document.getElementsByTagName("td"); 
        var i = 0;
        while(cell[i] != undefined){
            alert(cell[i].innerHTML); //do some alert for test
            i++;
            }//end while
    </script>

You can also use the DOM way to obtain the cell value: Cells[0].firstChild.data也可以使用DOM方式获取单元格值: Cells[0].firstChild.data

Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html在我在http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html 上的帖子中阅读更多相关信息

<td class="virtualTd" onclick="putThis(this)">my td value </td>

function putThis(control) { 
    alert(control.innerText);
}

I found this as an easiest way to add row .我发现这是添加 row 的最简单方法。 The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .令人敬畏的是,即使它包含输入元素,它也不会更改已经存在的表格内容。

row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;

Here #table_body is the id of the table body tag .这里#table_body是表体标签的id。

Here is perhaps the simplest way to obtain the value of a single cell.这可能是获取单个单元格值的最简单方法。

document.querySelector("#table").children[0].children[r].children[c].innerText

where r is the row index and c is the column index其中 r 是行索引,c 是列索引

Therefore, to obtain all cell data and put it in a multi-dimensional array:因此,要获取所有单元格数据并将其放入多维数组中:

var tableData = [];  
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))}); 
var cell = tableData[1][2];//2nd row, 3rd column

To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].要访问此多维数组中特定单元格的数据,请使用标准语法:array[rowIndex][columnIndex]。

Make a javascript function制作一个javascript函数

function addSampleTextInInputBox(message) {
    //set value in input box
    document.getElementById('textInput').value = message + "";
    //or show an alert
    //window.alert(message);
}

Then simply call in your table row button click然后只需调用您的表格行按钮单击

<td class="center">
    <a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
        <span class="fa fa-plus"></span>
    </a>
</td>

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

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