【问题标题】:How to add an html form in D3?如何在 D3 中添加 html 表单?
【发布时间】:2015-04-28 11:25:32
【问题描述】:

我正在尝试创建一个输入表单,当单击该节点时,该表单会出现在 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; });

            }
        })
}

现在我无法添加其他输入。我希望可以在附加的 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">"})

我对编程非常陌生,希望有人能够为我指明正确的方向。


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

【问题讨论】:

    标签: html forms input d3.js


    【解决方案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 + ">"
    })
    

    【讨论】:

    • 非常感谢。我知道这将是一些基本的东西!我现在遇到的问题是,虽然输入框在那里,但我无法单击它们来编辑内容,因此也无法编辑节点。这在追加(“输入”)中是可能的,但在 html 表单中是不可能的。
    • 您可以使用 vanilla d3 附加输入表单,您只需要指定要附加的输入类型,如下所示:.append('input').attr({type: 'input type you want', value: 'your values that can be called with a function'})
    猜你喜欢
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    相关资源
    最近更新 更多