jQuery:用动态HTML替换HTML而不是追加

时间:2016-12-01 22:33:09

标签: javascript jquery html

到目前为止,我已经获得了此代码:

<div id="myId" class="myClass">Hello world!</div>

这会附加

#myContainer
正如人们所料,

$("#myContainer").html("<div/>", { "id": "myId", "class": "myClass", "html": "Hello world!" });

但我不想追加,而是想让它取代内容。 我想象这样的事情:

$()

1 个答案:

答案 0 :(得分:1)

实际上,这很容易做到,您只需要再次在jquery()(或$("#myContainer").html($("<div/>", { "id": "myId", "class": "myClass", "html": "Hello world!" })); ,如果您愿意)包装动态HTML:

import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Translator extends Application {
    private static final double W = 400, H = 400;
    private static final double S = 50;

    public void start(Stage stage) {
        Rectangle rec = new Rectangle(W / 2 - S / 2,H / 2 - S / 2,S,S);

        TranslateTransition transition = new TranslateTransition(Duration.millis(500), rec);
        transition.setOnFinished(t -> {
            rec.setX(rec.getTranslateX() + rec.getX());
            rec.setY(rec.getTranslateY() + rec.getY());
            rec.setTranslateX(0);
            rec.setTranslateY(0);
        });

        Pane root = new Pane(rec);
        Scene scene = new Scene(root,W,H);

        root.setOnMousePressed(e -> {
            transition.stop();
            transition.setToX(e.getX() - S / 2 - rec.getX());
            transition.setToY(e.getY() - S / 2 - rec.getY());
            transition.playFromStart();
        });

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

尽管这种方法非常好,但我想知道是否有更优雅/高效的方法。