2012-12-07 20 views
2

我想在使用javascript動態創建的SVG內部創建一個簡單文本輸入數組。javascript生成的SVG中的外來物體

首先,我是這樣做的PHP和那裏的片段是這樣的:

for ($row=0; $row<7; $row++) 
{ 
for ($col=0; $col<7; $col++) 
{ 
    $fx=130+100*$col; 
    $fy=120+100*$row; 
    echo "<foreignObject x="".$fx."" y="".$fy."" width="50" height="80">\n<body xmlns="http://www.w3.org/1999/xhtml">\n<form><input type="text" width="1"/ style="font-size:48px; border:none;"></form>\n</body>\n</foreignObject>"; 
} 
}  

然後在javascript中我會嘗試像這樣的單一實例,但我沒有得到這個工作。

var field = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject"); 
field.setAttribute("x", "130"); 
field.setAttribute("y", "120"); 
field.setAttribute("width", "50"); 
field.setAttribute("height", "80"); 
mySvg.appendChild(field.cloneNode(true)); 
var s = '<body xmlns="http://www.w3.org/1999/xhtml"><form><input type="text" width="1" style="font-size:48px; border:none;"></form></body>'; 
var s1 = document.createElement(s); 
field.appendChild(s1); 
</script> 

任何提示?或者我應該切換到完全不同的實現(例如CSS)?

回答

1

document.createElement需要一個元素名稱作爲參數並創建一個元素,它不會解析任何html/xml內容。您可以使用DOMParser解析標記字符串。

至於PHP你可能需要escape echo中的內部雙引號。

+0

謝謝。我將看看DOMParser。 (即使使用非轉義引號,PHP代碼也適用於我。) – user1885537