如何通过 JavaScript 获取 html table td 单元格值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10057226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:39:43  来源:igfitidea点击:

How to get html table td cell value by JavaScript?

javascripthtml-tablecell

提问by user661684

I have an HTML table created with dynamic data and cannot predict the number of rows in it. What I want to do is to get the value of a cell when a row is clicked. I know to use td onclick but I do not know how to access the cell value in the Javascript function.

我有一个用动态数据创建的 HTML 表,无法预测其中的行数。我想要做的是在单击一行时获取单元格的值。我知道使用 td onclick 但我不知道如何访问 Javascript 函数中的单元格值。

The value of the cell is actually the index of a record and it is hidden in the table. After the record key is located I can retrieve the whole record from db.

单元格的值实际上是记录的索引,它隐藏在表格中。找到记录键后,我可以从数据库中检索整个记录。

How to get the cell value if I do not know the row index and column index of the table that I clicked?

如果我不知道我单击的表的行索引和列索引,如何获取单元格值?

回答by David says reinstate Monica

Don't use in-line JavaScript, separate your behaviour from your data and it gets much easier to handle. I'd suggest the following:

不要使用内嵌 JavaScript,将您的行为与数据分开,这样会更容易处理。我建议如下:

var table = document.getElementById('tableID'),
    cells = table.getElementsByTagName('td');

for (var i=0,len=cells.length; i<len; i++){
    cells[i].onclick = function(){
        console.log(this.innerHTML);
        /* if you know it's going to be numeric:
        console.log(parseInt(this.innerHTML),10);
        */
    }
}

var table = document.getElementById('tableID'),
  cells = table.getElementsByTagName('td');

for (var i = 0, len = cells.length; i < len; i++) {
  cells[i].onclick = function() {
    console.log(this.innerHTML);
  };
}
th,
td {
  border: 1px solid #000;
  padding: 0.2em 0.3em 0.1em 0.3em;
}
<table id="tableID">
  <thead>
    <tr>
      <th>Column heading 1</th>
      <th>Column heading 2</th>
      <th>Column heading 3</th>
      <th>Column heading 4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>43</td>
      <td>23</td>
      <td>89</td>
      <td>5</td>
    </tr>
    <tr>
      <td>4</td>
      <td>3</td>
      <td>0</td>
      <td>98</td>
    </tr>
    <tr>
      <td>10</td>
      <td>32</td>
      <td>7</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

JS Fiddle proof-of-concept.

JS Fiddle 概念验证

A revised approach, in response to the comment (below):

针对评论(如下)的修订方法:

You're missing a semicolon. Also, don't make functions within a loop.

你少了一个分号。另外,不要在循环中创建函数。

This revision binds a (single) named function as the clickevent-handler of the multiple <td>elements, and avoids the unnecessary overhead of creating multiple anonymous functions within a loop (which is poor practice due to repetition and the impact on performance, due to memory usage):

此修订版绑定了一个(单个)命名函数作为click多个<td>元素的事件处理程序,并避免了在循环内创建多个匿名函数的不必要开销(这是一种糟糕的做法,由于重复和对性能的影响,由于内存使用) ):

function logText() {
  // 'this' is automatically passed to the named
  // function via the use of addEventListener()
  // (later):
  console.log(this.textContent);
}

// using a CSS Selector, with document.querySelectorAll()
// to get a NodeList of <td> elements within the #tableID element:
var cells = document.querySelectorAll('#tableID td');

// iterating over the array-like NodeList, using
// Array.prototype.forEach() and Function.prototype.call():
Array.prototype.forEach.call(cells, function(td) {
  // the first argument of the anonymous function (here: 'td')
  // is the element of the array over which we're iterating.

  // adding an event-handler (the function logText) to handle
  // the click events on the <td> elements:
  td.addEventListener('click', logText);
});

function logText() {
  console.log(this.textContent);
}

var cells = document.querySelectorAll('#tableID td');

Array.prototype.forEach.call(cells, function(td) {
  td.addEventListener('click', logText);
});
th,
td {
  border: 1px solid #000;
  padding: 0.2em 0.3em 0.1em 0.3em;
}
<table id="tableID">
  <thead>
    <tr>
      <th>Column heading 1</th>
      <th>Column heading 2</th>
      <th>Column heading 3</th>
      <th>Column heading 4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>43</td>
      <td>23</td>
      <td>89</td>
      <td>5</td>
    </tr>
    <tr>
      <td>4</td>
      <td>3</td>
      <td>0</td>
      <td>98</td>
    </tr>
    <tr>
      <td>10</td>
      <td>32</td>
      <td>7</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

JS Fiddle proof-of-concept.

JS Fiddle 概念验证

References:

参考:

回答by pbfy0

This is my solution

这是我的解决方案

var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
    console.log("My contents is \"" + cells[i].innerHTML + "\"");
}

回答by Afshin Mehrabani

You can use:

您可以使用:

<td onclick='javascript:someFunc(this);'></td>

With passing thisyou can access the DOM object via your function parameters.

通过传递它,您可以通过函数参数访问 DOM 对象。

回答by Tom

I gave the table an id so I could find it. On onload (when the page is loaded by the browser), I set onclick event handlers to all rows of the table. Those handlers alert the content of the first cell.

我给了桌子一个 id,这样我就可以找到它。在 onload(当页面被浏览器加载时),我将 onclick 事件处理程序设置为表的所有行。这些处理程序会提醒第一个单元格的内容。

<!DOCTYPE html>
<html>
    <head>
        <script>
            var p = {
                onload: function() {
                    var rows = document.getElementById("mytable").rows;
                    for(var i = 0, ceiling = rows.length; i < ceiling; i++) {
                        rows[i].onclick = function() {
                            alert(this.cells[0].innerHTML);
                        }
                    }
                }
            };
        </script>
    </head>
    <body onload="p.onload()">
        <table id="mytable">
            <tr>
                <td>0</td>
                <td>row 1 cell 2</td>
            </tr>
            <tr>
                <td>1</td>
                <td>row 2 cell 2</td>
            </tr>
        </table>    
    </body>
</html> 

回答by Dia

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

……………………

  <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. Courseis is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. coursesis an ArrayList of Course objects.

我在 JSP 中编写了 HTML 表。 当然是一种类型。例如Course cs, cs=Course 类型的对象,它有两个属性:id、title。 课程是课程对象的ArrayList。

The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:

HTML 表格在每个单元格中显示所有课程标题。所以该表只有 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" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier. It works.

这意味着在用户选择表格单元格后,例如“Course2”,课程的标题“Course2”将转到 URL 指向用户的页面:http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp。“Course2”将到达FoundS.jsp 页面。“Course2”的标识符是courseId。要声明将保留 CourseX 的变量 courseId,您可以输入“?” 在 URL 之后和标识符旁边。有用。