2015-04-28 54 views
4

我試圖創建一個輸入窗體,該窗體在點擊節點時在d3有向力圖中顯示在一個節點上。用戶輸入的信息會更新節點的屬性 - 比如名稱會改變標題,角色是節點的顏色等等。我設法用一個輸入來描述一個屬性,使用下面的函數:如何在D3中添加html表單?

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正在工作,因爲我可以在consol中看到它,但我似乎無法使其可編輯。我一定在做一些根本性錯誤的事情,希望有人能指出我正確的方向。下面是完整的代碼的小提琴至今 - https://jsfiddle.net/VGerrard/91e7d5g9/2/

回答

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 + ">" 
}) 
+0

千恩萬謝的。我知道這將是基本的東西!我現在遇到的麻煩是,儘管輸入框在那裏,我不能點擊它們來編輯內容,因此也不能編輯節點。這是可能的附加(「輸入」),但不是在HTML表單。 – Gerrard

+0

你可以使用vanilla d3添加輸入表單,你只需要指定你正在追加的輸入類型,就像這樣:'.append('input')。attr({type:'你想要的輸入類型',值:'你的值可以用函數調用'})' – tomtomtom