如何在 D3 中添加 html 表单?

Ger*_*ard 5 html forms input d3.js

我正在尝试创建一个输入表单,当单击节点时,该表单出现在 d3 定向力图中的节点上。用户输入的信息将更新节点的属性 - 例如名称将更改标题,角色将更改节点的颜色等。我设法使用一个描述一个属性的输入来实现这一点,并具有以下功能:

    function nodeForm(d) {
    var p = this.parentNode;
    var el = d3.select(this);
    var p_el = d3.select(p);

    var form = p_el.append("foreignObject");

    var input = form
    .attr("width", 300)
    .attr("height", 100)
    .attr("class", "input")
    .append("xhtml:form")
    .html(function(d) {return "<strong>Name:</strong>"}) 
    .append("input")
    .attr("value", function(d) {this.focus(); return d.name})
    .attr("style", "width: 200px;")
    .on("keypress", function() {

           if (!d3.event)
            d3.event = window.event;

            //Prevents total update
            var e = d3.event;
            if (e.keyCode == 13){
            if (typeof(e.cancelBubble) !== 'undefined') // IE
                e.cancelBubble = true;
            if (e.stopPropagation)
                e.stopPropagation();
                e.preventDefault();

            var text = input.node().value;

            d.name = text;
            el.text(function(d) { return d.name; });

            }
        })
}
Run Code Online (Sandbox Code Playgroud)

现在我在添加其他输入时遇到了麻烦。我希望可以在附加的 html 函数中添加一个输入框(如下所示),但它无法识别值,并且输入框 - 尽管它确实出现 - 不允许输入任何内容。

    .html(function(d) {return "<strong>Name:</strong> <input type = 'text' value = "d.name"> <br> <strong>Role:</strong> <input type = 'text' value = "d.role"> <br> <strong>Name:</strong> <input type = 'text' value = "d.tribe">"})
Run Code Online (Sandbox Code Playgroud)

我对编程很陌生,希望有人能够指出我正确的方向。


我仍然无法让弹出式输入框工作。使用各种方法(包括将其附加到节点组,使用 .html 附加它,调用 html 文件中的表单,将其包括在 mouseup 函数中,使用工具提示等),我所做的就是得到相同的结果 - 我可以看到输入框但我无法编辑它们。我认为foreignObject 正在工作,因为我可以在控制台中看到它,但我似乎无法使其可编辑。我一定在做一些根本错误的事情,我希望有人能指出我正确的方向。这是迄今为止完整代码的小提琴 - https://jsfiddle.net/VGerrard/91e7d5g9/2/

tom*_*tom 1

您忘记在字符串和值之间添加+,这可能会得到您想要做的事情

.html(function(d) {
    return "<strong>Name:</strong> <input type = 'text'
     value = " + d.name + "> <br> <strong>Role:</strong> <input type =
     'text' value = " + d.role + "> <br> <strong>Name:</strong> <input type
     = 'text' value = " + d.tribe + ">"
})
Run Code Online (Sandbox Code Playgroud)