简体   繁体   中英

JQuery/javascript how do I get the ID of an object?

function cat() {


    this.getMyID = function() { alert(this.id); } ;

}

var bob = new cat();

// I want it to say 'bob'
bob.getMyID();

http://jsfiddle.net/n7eHj/

alerts undefined, any ideas?

I'll elaborate, this is what I want to do - insert into an onclick method of a button something that calls another function, eg:

function cat() {

   this.render = function() { $('#myButton').attr('onclick', 'this.meow()'); };

}

var bob = new cat();
bob.render();

However this will fail because 'this.meow' is nonsense. If I knew the ID, ie. bob, then I could change it to do .attr('onclick', theID + '.meow()'); }; .attr('onclick', theID + '.meow()'); };

Regarding your update:

Assuming cat has a method meow , you should do the following:

function Cat() {
   var that = this;
   this.render = function() { 
       $('#myButton').click(function() {
           that.meow();
       });
   };
}

// assuming it exists something like
Cat.prototype.meow = function() {/*...*/};

You already have a reference to the object ( this ), you don't need to know in which variable it is stored.

You should also use jQuery's click function to assign a click handler. But be careful though as this would add a new click handler every time you call render() .

Generic "objects" don't have IDs - they don't know what variables are bound to them.

Furthermore you could have said:

var bob = new cat();
var alice = bob;

at which point you have a schizophrenic cat.

It alerts undefined because cat doesn't have an "id" property. No sure how you expected it to have an id.

I will try...

I'll elaborate, this is what I want to do - insert into an onclick method of a button something that calls another function,

Here is some code... is it close?

var bobthefunction = function () {
    // do crazy stuff
   }

$("buttonname").attr("onclick",bobthefunction);

or

$("buttonname").click(bobthefunction);

What you can do is use closures:

function cat() {
    this.render = function() 
    { 
        $('#myButton').click(function(self ) 
        {
            return function() { self.meow() }
        }(this));
    }
}

By the way, it's not recommended to attach event handlers using .attr - it simply doesn't always work in all browsers/cases. You better use .bind or an even shortcut like .click

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM