0

实际上,为了避免 jquery 的东西,我打算直接在表列表中添加行。

您能否通过将值设置为 htmltable 中的字符串或其他方式(HTMLUNIT)来帮助我动态添加行。

--------------
<table id="list4" class="scroll">
</table>
------------------------

package com.test;

import java.io.IOException;
import java.net.MalformedURLException;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomCharacterData;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableCell;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;

public class TestMain {

  public static void main(String args[])
        throws FailingHttpStatusCodeException, MalformedURLException, IOException {
    final String htmlContent = "<html><head><title>foo</title></head><body><table id='table1'><tr id='row1'><td>cell1</td></tr><tr id='row2'><td>cell2</td></tr><tr id='row3'><td>cell3</td></tr><tr id='row4'><td>cell4</td></tr><tr id='row5'><td>cell5</td></tr><tr id='row6'><td>cell6</td></tr></table></body></html>";
    WebClient webClient = new WebClient();
    final HtmlPage page = loadPage(htmlContent);
    final HtmlTable table = page.getHtmlElementById("list4");
    // want to add to the new row here
    for (final HtmlTableRow row : table.getRows()) {
      System.out.println("Found row");
      for (final HtmlTableCell cell : row.getCells()) {
        System.out.println("   Found cell: " + cell.asText());
      }
    }
  }
}
4

2 回答 2

0

这段代码基本上创建了一个新的行和单元格。然后用一些文本填充单元格,然后将元素附加到它们的父级。

HtmlTableRow newRow = page.createElement("tr");
HtmlTableCell newCell = page.createElement("td");
Text cellContent = page.createTextNode("Hello World");
newCell.appendChild(cellContent);
newRow.appendChild(newCell);
table.appendChild(newRow); 
// you can also have `table.insertBefore(newRow, exisitingRow);`
于 2013-02-10T04:15:07.000 回答
0

我做了,稍加修改。它对我有用。

    final HtmlTable table = page.getHtmlElementById("highlight");

    HtmlTableRow newRow = (HtmlTableRow) page.createElement("tr");
    HtmlTableCell newCell = (HtmlTableCell) page.createElement("td");
    DomText cellContent =  (DomText) page.createTextNode("Welcome Sireesh");

    newCell.appendChild((org.w3c.dom.Node) cellContent);
    newRow.appendChild(newCell);
    table.appendChild(newRow); 
于 2013-02-10T12:50:05.760 回答