views:

33

answers:

2

I want to my div ids to correspond to items in a database. Based on an id my app will pull appropriate content from a database.

Hence when I use .click() to handle a click I need to pass the Id of the div being clicked to the function that handles it. How do I do this?

+5  A: 

Inside your click event handler function, the context (the this keyword) refers to the DOM element that triggered the event, you can get the id from it, for example:

$('div[id]').click(function () { // all divs that have an id attribute
  var id = this.id; // or $(this).attr('id');

  someOtherFunction(id);
});
CMS
+1  A: 

In the context of a click handler this corresponds to the DOM element which was clicked. You can use it to extract the id:

$('div').click(function() {
    // Get the id of the clicked div
    var id = this.id;
    // Do something with it ...
});
Darin Dimitrov