您还可以使用 JavaScript 进行追加。
final WebEngine appendEngine = view.getEngine();
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent event) {
appendEngine.executeScript(
"document.getElementById('content').appendChild(document.createTextNode('World!'));"
);
}
});
有时我发现使用 jQuery 操作 DOM 比使用 Java Document 或原生 JavaScript DOM 接口更简单。
final WebEngine appendEngine = view.getEngine();
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent event) {
executejQuery(appendEngine, "$('#content').append('World!');");
}
});
...
private static Object executejQuery(final WebEngine engine, String script) {
return engine.executeScript(
"(function(window, document, version, callback) { "
+ "var j, d;"
+ "var loaded = false;"
+ "if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {"
+ " var script = document.createElement(\"script\");"
+ " script.type = \"text/javascript\";"
+ " script.src = \"http://code.jquery.com/jquery-1.7.2.min.js\";"
+ " script.onload = script.onreadystatechange = function() {"
+ " if (!loaded && (!(d = this.readyState) || d == \"loaded\" || d == \"complete\")) {"
+ " callback((j = window.jQuery).noConflict(1), loaded = true);"
+ " j(script).remove();"
+ " }"
+ " };"
+ " document.documentElement.childNodes[0].appendChild(script) "
+ "} "
+ "})(window, document, \"1.7.2\", function($, jquery_loaded) {" + script + "});"
);
}
无论您使用 Uluk 所使用的 Java Document API,还是 JavaScript 或 JQuery API,Uluk 出色答案中的所有其他观点仍然适用。