Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中向SVG文档添加文本_Javascript_Jquery_Svg - Fatal编程技术网

在javascript中向SVG文档添加文本

在javascript中向SVG文档添加文本,javascript,jquery,svg,Javascript,Jquery,Svg,我正在尝试使用javascript向SVG文档中的元素添加一个文本元素 我的代码如下所示 function addText(x,y,val){ var newtxt = document.createElementNS("http://www.w3.org/2000/svg", "text"); $newtxt = $(newtxt); $newtxt.attr('x',x); $newtxt.attr('y',y); $newtxt.attr('font

我正在尝试使用javascript向SVG文档中的
元素添加一个文本元素 我的代码如下所示

function addText(x,y,val){
    var newtxt = document.createElementNS("http://www.w3.org/2000/svg", "text");
    $newtxt = $(newtxt);
    $newtxt.attr('x',x);
    $newtxt.attr('y',y);
    $newtxt.attr('font-size','100');
    $newtxt.val(val);
    $newtxt.appendTo($('g'));
}
但当我运行它时,文本不会显示。 元素被添加到
元素中,但未设置值。。
有什么办法解决这个问题吗?

我认为需要创建一个文本节点来保存字符串,并将其附加到SVG文本元素中

var svgNS = "http://www.w3.org/2000/svg";
var newText = document.createElementNS(svgNS,"text");
newText.setAttributeNS(null,"x",x);     
newText.setAttributeNS(null,"y",y); 
newText.setAttributeNS(null,"font-size","100");

var textNode = document.createTextNode(val);
newText.appendChild(textNode);
document.getElementById("g").appendChild(newText);

上有一个工作示例。

我已经验证了这是正确的。(使用createTextNode。)应标记为答案。Bill可以更新它指向404页的链接。虽然此代码片段可以解决问题,但确实有助于提高您的帖子质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。还请尽量不要用解释性注释挤满您的代码,因为这会降低代码和解释的可读性!请解释一下这是如何工作的,Casey,以及为什么我们需要NS和空值。诀窍是属性
innerHTML
。有趣的是,这个节点没有
innerText
var txt = document.createElementNS(svgNS, 'text');
txt.setAttributeNS(null, 'x', x);
txt.setAttributeNS(null, 'y', y);
txt.setAttributeNS(null,'font-size','100');
txt.innerHTML = val;
document.getElementById("g").appendChild(txt);