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

How to get html table td cell value by JavaScript?

本文关键字:td 单元格 html 何通过 JavaScript 获取      更新时间:2023-09-26

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

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

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

不要使用内联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小提琴概念验证。

针对评论意见(见下文)的修订方法:

您缺少分号。另外,不要在循环中创建函数。

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

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小提琴概念验证。

引用:

  • Array.prototype.forEach() .
  • document.getElementById() .
  • document.getElementsByTagName() .
  • document.querySelectorAll() .
  • EventTarget.addEventListener() .
  • Function.prototype.call() .
这是我

的解决方案

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

您可以使用:

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

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

我给表一个id,这样我就可以找到它。在加载时(当浏览器加载页面时),我将 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> 

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

  <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>

我用JSP编写了HTML表。课程是一种类型。例如,课程 cs,cs= 课程类型的对象,它有 2 个属性:id、标题。课程是课程对象的数组列表。

HTML 表格显示每个单元格中的所有课程标题。所以该表只有 1 列:课程1课程2课程3......旁白:

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

这意味着在用户选择表格单元格(例如"Course2")后,课程的标题"Course2"将转到URL引导用户的页面:http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp。"Course2"将到达FoundS.jsp页面。"Course2"的标识符是 courseId。要声明变量 courseId(其中将保留 CourseX),请在 URL 后加上一个"?",并在它旁边加上标识符。它有效。