문제

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/

도움이 되었습니까?

해결책

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.

다른 팁

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
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top