How to pass Id of a div that is clicked to a function that handles the click in jQuery
I want to my div ids to correspond to items in a database. Based 开发者_JAVA百科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?
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);
});
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 ...
});
精彩评论