2016-06-16 49 views
0

我有以下对象传递给我一个数组里面的函数:是否有可能从javascript中获取特定属性的对象数组?

[ { id: 'WA1WA1WAbWA2WAaWAbWA9WA6-WAdWA2WAaWAd-4WAbWAcWA3-WAbWA3WA7WAa-WAcWAbWA8WA9WAcWA9WA9WA9WA3WA3WA3WA9', 
obj: '<svg data="BusinessProductFigure" x="484.171875" y="123" id="WA1WA1WAbWA2WAaWAbWA9WA6-WAdWA2WAaWAd-4WAbWAcWA3-WAbWA3WA7WAa- WAcWAbWA8WA9WAcWA9WA9WA9WA3WA3WA3WA9" 
xmlns="http://www.w3.org/2000/svg" version="1.1"><rect x="4" y="4" 
width="60" height="14" fill="rgb(299,299,162)" stroke-linejoin="round" 
stroke="rgb(299,299,162)" stroke-width="1"/></svg>' } ] 

是有可能得到单独的变量,是SVG标记中的X和Y值?是否有任何条件或分隔符可以用于某种方式?

+0

使用[的DOMParser](https://developer.mozilla.org/en/docs/Web/API/DOMParser)来解析它,然后从DOM中读取值。 –

+0

@RobertLongson我得到了文档,但我现在如何访问各个变量? – Arihant

+0

我想通了。刚刚使用过doc.getElementsByTagName [“svg”]。getAttribute(“x”);非常感谢! – Arihant

回答

1

使用DOMParser像这样:

var x = [ { id: 'WA...', 
 
      obj: '<svg data="BusinessProductFigure" x="484.171875" y="123" id="WA..." xmlns="http://www.w3.org/2000/svg" version="1.1"><rect x="4" y="4" width="60" height="14" fill="rgb(299,299,162)" stroke-linejoin="round" stroke="rgb(299,299,162)" stroke-width="1"/></svg>' } ] 
 
      
 
var dom = new DOMParser().parseFromString(x[0].obj, 'image/svg+xml'); 
 

 
alert(dom.documentElement.getAttribute("x"));

3

var arr = [{ 
 
    id: 'JKIU', 
 
    obj: '<svg data="BusinessProductFigure" x="484.171875" y="123" id="FRRR" xmlns="http://www.w3.org/2000/svg" version="1.1" > <rect x="4" y="4" width="60" height="14" fill="rgb(299,299,162)" stroke-linejoin="round" stroke="rgb(299,299,162)" stroke-width="1"/></svg>' 
 
}]; 
 

 
var div = document.createElement('div'); 
 

 
div.innerHTML = arr[0].obj; 
 

 
// var svg = div.querySelector('svg'); 
 
var svg = div.firstChild; 
 

 
var x = svg.getAttribute('x'); 
 
var y = svg.getAttribute('y'); 
 

 
console.log(x, y);

+0

而不是'querySelector'你可以做'firstChild' – 4castle

+0

@ 4castle确定虐待更新谢谢 – DININDU

相关问题