【问题标题】:How to get html table td cell value by JavaScript?如何通过 JavaScript 获取 html 表格 td 单元格值?
【发布时间】:2012-04-20 21:11:00
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript html-table cell


    【解决方案1】:

    你可以使用:

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

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

    【讨论】:

    • 在有 jQuery 和许多其他库鼓励不显眼的 JavaScript 的时代,内联函数并不是最好的方法。
    • 内联处理程序没有问题。不是每个人都是“不引人注目的 JavaScript”宗教的一部分。
    【解决方案2】:

    不要使用内联 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.

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

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

    此版本将(单个)命名函数绑定为多个 &lt;td&gt; 元素的 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 Fiddle proof-of-concept.

    参考资料:

    【讨论】:

    • 你少了一个分号。另外,不要在循环中创建函数。
    • @localhost:你说得对,我已经编辑以更正省略的分号,并提供了一个替代解决方案,它使用命名函数,而不是多个循环创建的匿名函数。感谢您的评论!
    【解决方案3】:

    我给了表格一个 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> 
    

    【讨论】:

      【解决方案4】:

      这是我的解决方案

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

      【讨论】:

      【解决方案5】:

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

        <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 表格。 Course 是一种类型。例如 Course cs, cs= 类型为 Course 的对象,它有 2 个属性:id、title。 courses 是 Course 对象的 ArrayList。

      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。要声明将保留 CourseX 的变量 courseId,请输入“?”在 URL 之后,在它旁边是标识符。 它有效。

      【讨论】:

        猜你喜欢
        • 2014-08-03
        • 2012-12-12
        • 2013-08-01
        • 2012-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-26
        相关资源
        最近更新 更多