3

我想根据 HTML 表填充对象列表。假设我有以下课程:

class Employee
{
  String name;
  String department;
  num salary;

  ...methods
}

在我的 HTML 中,我有下表:

<table class="table" id="employeeTable">
   <thead>
   <tr>
     <th>Name
     <th>Departament
     <th>Salary  
     <tbody id="employeeTableBody">
   <tr>
     <td> John
     <td> 1
     <td> 1500
   <tr>
     <td> Mary
     <td> 2
     <td> 2500
              ...etc    

</table>

那么,如何查询表,获取其行,然后获取其单元格以填充我的员工列表(在本例中)?

我尝试使用类似的东西:

    TableElement table = query("#employeesTable");
    Element tableBody = query("#employeesTableBody");

但是我在 TableElement 或 Element 中找不到合适的方法来返回 TableRowElement,或者它的单元格。我也尝试获取子节点,但没有成功。

完成此任务的伪算法将是这样的:

1. Get the table
2. For each row of the table
2.a Create a new Employee object based on the value of each cell of the row.
2.b Append this object to the Employee List.
3. End
4

1 回答 1

6

这里的HTML:

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <title>Scratchweb</title>
    <link rel="stylesheet" href="scratchweb.css">
  </head>
  <body>
    <table id="employeeTable">
      <tr>
        <th>Name</th>
        <th>Departament</th>
        <th>Salary</th>
      </tr>
      <tr>
        <td>John</td>
        <td>1</td>
        <td>1500</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>2</td>
        <td>2500</td>
      </tr>    
    </table>

    <script type="application/dart" src="web/scratchweb.dart"></script>
    <script src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
  </body>
</html>

这是飞镖:

import 'dart:html';
import 'dart:math';

class Employee {
  String name;
  String department;
  num salary;

  Employee({this.name, this.department, this.salary});
  String toString() => '<employee name="$name" department="$department" salary="$salary">';
}

void main() {
  var employees = new List<Employee>();
  var table = query("table#employeeTable");
  for (TableRowElement row in table.rows) {
    if (row.cells.length != 3) {
      print("Malformed row: $row");
      continue;
    }
    if ((row.cells[0] as TableCellElement).tagName == "TH") {
      print("Skipping header");
      continue;
    }
    var cells = row.cells;
    var employee = new Employee(
        name: cells[0].text,
        department: cells[1].text,
        salary: parseDouble(cells[2].text));
    employees.add(employee);
  }
  print(employees);
}

如果您同意这个答案,请记住接受它。每次我成功回答问题时,我的老板都会喂我一片培根;)

于 2012-10-30T20:22:10.877 回答