javascript 如何添加 使用 d3.js selection.text() 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12882885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add using d3.js selection.text() method
提问by Ryan
selection.text(' ')
appears to convert the special characters so it renders the actual text, rather than a space like I want. Is there a way to prevent the text()
method on selections from doing this escaping for me? For context, this is a table cell that is empty for some elements in the selection, and I need the space in there so that the cells render properly.
selection.text(' ')
似乎转换特殊字符,因此它呈现实际文本,而不是像我想要的空格。有没有办法阻止text()
选择的方法为我做这种逃避?对于上下文,这是一个表格单元格,对于选择中的某些元素是空的,我需要在那里留出空间,以便单元格正确呈现。
采纳答案by Matt Esch
d3_selectionPrototype.text = function(value) {
return arguments.length < 1 ? this.node().textContent : this.each(typeof value === "function" ? function() {
var v = value.apply(this, arguments);
this.textContent = v == null ? "" : v;
} : value == null ? function() {
this.textContent = "";
} : function() {
this.textContent = value;
});
};
The important line here is that calling .text() on a selection will set the textContent property on each element. So the correct thing to do in your case is use
这里重要的一点是在选择上调用 .text() 将在每个元素上设置 textContent 属性。所以在你的情况下正确的做法是使用
selection.text(' ');
So if you want to use spaces then you simply have to use spaces in the text, not html encoded spaces. If you want to use html encoded chars then you have to treat the content as innerHTML.
因此,如果您想使用空格,那么您只需在文本中使用空格,而不是 html 编码的空格。如果要使用 html 编码的字符,则必须将内容视为 innerHTML。
selection.html(' ');
回答by Ian Roberts
Use a JavaScript Unicode escape rather than an HTML entity.
in HTML denotes the Unicode character U+00A0 so
使用 JavaScript Unicode 转义而不是 HTML 实体。
在 HTML 中表示 Unicode 字符 U+00A0 所以
selection.text('\u00A0')
should do what you want.
应该做你想做的。