How to get clicked node id in cytoscape.js?

This example is in the documentation:

  cy.on('click', function(evt){
      console.log( 'clicked ' + this.id() );
});

Results in:

Uncaught TypeError: Object [object Object] has no method 'id' 

And evt.cyTarget.data () returns undefined.

+5
source share
3 answers

The .id () function works with elements, but you do not have an element in the event handler. You are attached to the kernel without any delegate element selector, so you are attached to the kernel itself - this means that the link to thispoints to cy.

This is probably what you meant:

cy.on('click', 'node', function(evt){
      console.log( 'clicked ' + this.id() );
});
+6
source

I use this for 2.x:

    cy.on('tap', 'node', function (evt) {
         console.log(evt.cyTarget.id())
    });

Or for 3.x:

    cy.on('tap', 'node', function (evt) {
         console.log(evt.target.id())
    });
+5
source

, eles.data(). , id node,

console.log('clicked ' + this.data('id'));
+3

All Articles