最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get ID of clicked Element in snap.svg - Stack Overflow

programmeradmin3浏览0评论

What is the best (cross browser) approach to get the attribute id (or basically any attribute that helps me identifying the Element on which the event happened) within an event handling function (e.g. click callback function) of snap.svg /

Here is some code. What I have tried seems to work in latest Chrome and FF, but I wonder if there is a better approach.

    //add an Element, set id
    var mySvg = Snap('#mySvg');
    var myRect = mySvg.rect(10,10,200,100);
    myRect.attr({id:'myId'});

    //register click callback
    myRect.click(clickCallback);

    //click callback
    var clickCallback = function(event) {
       // how do I get the id of the clicked element?
       // is this cross browser valid?
       var id = event.target.attributes.id.nodeValue;
    };

What is the best (cross browser) approach to get the attribute id (or basically any attribute that helps me identifying the Element on which the event happened) within an event handling function (e.g. click callback function) of snap.svg http://snapsvg.io/

Here is some code. What I have tried seems to work in latest Chrome and FF, but I wonder if there is a better approach.

    //add an Element, set id
    var mySvg = Snap('#mySvg');
    var myRect = mySvg.rect(10,10,200,100);
    myRect.attr({id:'myId'});

    //register click callback
    myRect.click(clickCallback);

    //click callback
    var clickCallback = function(event) {
       // how do I get the id of the clicked element?
       // is this cross browser valid?
       var id = event.target.attributes.id.nodeValue;
    };
Share Improve this question asked Jan 24, 2014 at 16:13 mwallischmwallisch 1,8192 gold badges22 silver badges30 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

I think there's an issue with the current version of Snap and id, which is fixed in next release (0.2 which may be current by now) https://github./adobe-webplatform/Snap.svg/issues/166 so worth a read at some point.

However, I typically don't use an id like that for these cases, I would use 'this'. So with a handler, it can look something like...

var mySvg = Snap(400, 620);
var myRect = mySvg.rect(10,10,200,100);

var clickCallback = function(event) {
    this.attr({ fill: 'blue' });
};

myRect.click(clickCallback);

jsfiddle here http://jsfiddle/qgTdF/2/

This solution may work for you, and be preferable, but it depends ultimately if you need to do something else (in which case maybe post another question with the specific issue). It may also be worth trying the latest version (I think 0.2), if you need to fiddle a bit and specifically use the id.

发布评论

评论列表(0)

  1. 暂无评论