Question

I'm trying to get the Raphaël object by using the getById() function, however no matter what I try the function returns null.

Here is the Raphaël JS code I'm working with:

// 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?

Why doesn't paper.getById("test"); return the circle object?

I've defined the ID by both using attr() and data() yet nothing seems to work.

JsFiddle of the above code: http://jsfiddle.net/Mf9q6/

Était-ce utile?

La solution

Read the documentation carefully:

Returns you element by its internal ID.

This is not the same as the id attribute on the element. The id expected by Paper.getById() is Element.id

You probably want var getCircle = paper.getById(circle.id); which is just a reference to the same object as circle anyway.

Here's your fiddle, updated.

Autres conseils

If I understood your question correctly, you are trying to set id to your element. Then somewhere down the line get the element's id.

If it is the case then you are almost there:

// 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

EDIT

If you are trying to get the circle by the value, like in your example "test"

paper.forEach(function (el) 
{
    if (el.data("id") == "test")
        // return el - do what you want
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top