本文介绍了附加文本 WebEngine - JavaFX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将文本附加到 webengine?我试过这个:

How can I append text to webengine? I tried this:

public TabMessage(String title) {
    super(title);
    view = new WebView();
    engine = view.getEngine();
    engine.loadContent("<body></body>");
    view.setPrefHeight(240);
}

private void append(String msg){
    Document doc = engine.getDocument();
    Element el = doc.getElementById("body");
    String s = el.getTextContent();
    el.setTextContent(s+msg);
}

但是文档是null

推荐答案

您也可以使用 JavaScript 进行追加.

You can also use JavaScript to do the append.

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 文档或原生 JavaScript DOM 接口更简单.

I sometimes find it simpler to use jQuery to manipulate the DOM rather than the Java Document or native JavaScript DOM interfaces.

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 文档 API,还是使用 JavaScript 或 JQuery API,Uluk 出色答案中的所有其他要点仍然适用.

Whether you use the Java Document API, as Uluk has, or JavaScript or JQuery APIs, all of the other points in Uluk's excellent answer still apply.

这篇关于附加文本 WebEngine - JavaFX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:28