Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.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_Svg_Attributes_D3.js - Fatal编程技术网

Javascript 是否可以将SVG对象的自定义属性设置为数字而不是字符串?

Javascript 是否可以将SVG对象的自定义属性设置为数字而不是字符串?,javascript,svg,attributes,d3.js,Javascript,Svg,Attributes,D3.js,我将人工属性分配给SVG-G元素(SVG组对象)。我使用SVG转换移动组及其内容,并将组的x/y坐标及其宽度/高度存储在这些属性中 我正在使用D3 Javascript库和调用: embeddedElemContainer = nodeBoxContainer.append('svg:g') .attr('x', x) .attr('y', y) .attr('width', width) .attr('height', height) 结果如下: <g

我将人工属性分配给SVG-G元素(SVG组对象)。我使用SVG转换移动组及其内容,并将组的x/y坐标及其宽度/高度存储在这些属性中

我正在使用D3 Javascript库和调用:

embeddedElemContainer = nodeBoxContainer.append('svg:g')
    .attr('x', x)
    .attr('y', y)
    .attr('width', width)
    .attr('height', height)
结果如下:

<g transform="translate(13.585786437626904,31.585786437626904)" x="13.585786437626904" y="31.585786437626904" width="43.00000000000001" height="0"></g>

有没有办法将这些值直接存储为整数/双精度?

您可以覆盖d3的
attr
函数来嗅出数字并为您执行
parseInt
。这可能会在以后出现兼容性问题,因此最好创建一个新的
attrInt
函数,例如:

d3.selection.prototype.attrInt = function(name, value) {
  if(arguments.length == 1) {
    return parseInt(this.attr(name));
  } else {
    return this.attr(name, value);
  }
};

免责声明:我没有d3的经验,所以我不确定这是否是正确的原型;我只是从看了一下资料来源才发现的。:)

D3中的正常方法是拥有绑定到节点的数据列表。看。D3将其放入它创建/修改的DOM节点的
\uuuu data\uuu
属性中。在内部,D3提取该属性并将其作为参数传递给各种函数,但您当然可以自己直接访问它

还可以通过将任意数据结构与单个节点关联

如果没有其余的上下文,很难说,但下面是我认为您正在尝试做的修改版本:

var vis = d3.select("body").append("svg").attr("width", 400).attr("height", 300);

var groupData = {x: 100, y:100, height: 50, width: 50, theanswer : 42, thecolor: "blue", somedouble: 45.1651654 };

var embeddedElemContainer = vis.append('svg:g')
    .datum( groupData )
    .attr( 'id', 'mygroup' )
    .attr( 'x', function(d) { return d.x; } )
    .attr( 'y', function(d) { return d.y; } )
    .attr( 'height', function(d) { return d.height; } )
    .attr( 'width', function(d) { return d.width; } )

// the regular DOM way:
console.log(document.getElementById('mygroup').__data__)

// the D3 way:
console.log( d3.select('#mygroup').datum() );
两个
console.log
语句输出:

height: 50
somedouble: 45.1651654
theanswer: 42
thecolor: "blue"
width: 50
x: 100
y: 100

虽然这可能有效,但我认为D3有一个更干净的内置方法。看看我的答案。哦!非常感谢你的精彩解释。我必须阅读更多关于D3中元素的边界数据/属性的内容。从未想过将此功能用于我的目的。
height: 50
somedouble: 45.1651654
theanswer: 42
thecolor: "blue"
width: 50
x: 100
y: 100