html - 如何根据 Dart 中的表及其行填充列表?

标签 html list html-table dart

我想根据 HTML 表格填充对象列表。假设我有以下类(class):

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

最佳答案

这里是 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>

这是 Dart :

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);
}

如果您认可本回答,请记得采纳。每次我成功回答问题时,老板都会给我一片培根;)

关于html - 如何根据 Dart 中的表及其行填充列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13142889/

相关文章:

javascript - 空文本框上的 JQuery 默认文本

css - 独立于主滚动的网页内的可滚动 Div

javascript - 像 javascript 中的代码一样的小型 FSM

java - 如何检查一个列表的对象是否包含另一个列表的任何对象

javascript - 单击复选框将表行移动到另一个表

javascript - 获取 HTML 表格中的行数

image - 表格rowspan透明图像

html - 在与图像内联的 CSS 中自动调整标题大小

javascript - 将存储为 String 的 Array 转换为 Java String 中的 List 对象

r - 将邻接表转换为 R 中的二进制矩阵