2014-03-06 55 views
0

我试图通过使用getById()函数来获得拉斐尔对象,但是不管我尝试函数返回null。拉斐尔JS paper.getById()返回null

这里是拉斐尔JS代码,我的工作:

// Creates canvas 320 × 200 at 10, 50 
var paper = Raphael(10, 50, 320, 200); 

var circle = paper.circle(100, 100, 100); 
circle.attr({"fill": "#f00", "id": "test"}); 
circle.data("id", "test"); 

var getCircle = paper.getById("test"); 

alert(getCircle); //Returns null? 

为什么不paper.getById("test");回圆对象?

我已经都使用attr()data()但似乎没有任何工作定义的ID。

的jsfiddle上面的代码:http://jsfiddle.net/Mf9q6/

回答

2

仔细阅读documentation

将返回元素通过其内部ID

这与元素上的id属性不一样。预计编号为Paper.getById()的是Element.id

您可能想要var getCircle = paper.getById(circle.id);,它只是对circle的同一对象的引用。

Here's your fiddle, updated

+0

是啊,我现在看到这一点。我希望能够通过定义的ID访问对象。哦,我会找到另一个解决最初的问题:) – Axel

1

如果我理解正确你的问题,你想设置id你的元素。然后在该行的某处获取该元素的ID。

如果是的话,那么你就要成功了:

// Creates canvas 320 × 200 at 10, 50 
var paper = Raphael(10, 50, 320, 200); 

var circle = paper.circle(100, 100, 100); 
circle.attr({"fill": "#f00", "id": "test"}); 
circle.data("id", "test"); 

var getCircle = circle.data("id"); 

alert(getCircle); //Returns test 

编辑

如果您正试图通过价值得到了一圈,就像你们的榜样“测试”

paper.forEach(function (el) 
{ 
    if (el.data("id") == "test") 
     // return el - do what you want 
}); 
+0

不,我正试图使用​​指定的ID检索一个Rapheal对象。我知道你可以设置对象数据,但根据数据的值检索对象实际上是问题所在。 – Axel

+0

我编辑了所以你可以得到你的圈子基于'test' – Brian

+0

感谢您的解决方案,但是我决定出于性能原因与数组/键映射解决方案。我不想循环遍历整个纸张集以找到单个对象(因为我有很多对象,并且性能会受到影响)。将对象映射到数组中的特定键似乎最适合我的情况。 'paperObjects ['test'] //返回测试对象' – Axel