【问题标题】:Is it possible to get specific attribute form an array of objects in javascript?是否可以从 javascript 中的对象数组中获取特定属性?
【发布时间】:2016-06-16 13:24:59
【问题描述】:

我在一个函数的数组中将以下对象传递给我:

[ { 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 值?是否有任何条件或分隔符可以以某种方式使用?

【问题讨论】:

  • 使用DOMParser解析它,然后从DOM中读取值。
  • @RobertLongson 我得到了文档,但我现在如何访问各个变量?
  • 我想通了。刚刚使用 doc.getElementsByTagName["svg"].getAttribute("x");非常感谢!

标签: javascript arrays object svg delimiter


【解决方案1】:

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);

【讨论】:

  • 你可以用firstChild代替querySelector
【解决方案2】:

像这样使用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"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-26
    • 2019-11-22
    • 2018-05-24
    • 2013-03-10
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多