C.Roshan C.Roshan - 6 months ago 7
HTML Question

I need to get id from HTML using jQuery

This is my code:

$('.image1').click(function(){
$('.loader').show();
function preloadImages(images, callback) {
var count = images.length;
var loaded = 0;
$(images).each(function() {
$('<img>').attr('src', this).load(function() {
loaded++;
if (loaded === count) {
callback();
}
});
});
};

preloadImages(["../images/Wedding_p/large/1.jpg",
"../images/Wedding_p/large/2.jpg",
"../images/Wedding_p/large/3.jpg",
"../images/Wedding_p/large/4.jpg",
"../images/Wedding_p/large/5.jpg"], function() {
alert("DONE");
// In here I need to get id of '.image1' image.
}


this is html:

<div>
<img src = '1.jpg' data-id='1' class = 'image1'>
<img src = '2.jpg' data-id='2' class = 'image1'>
<img src = '3.jpg' data-id='3' class = 'image1'>
</div>


When I click on the image I need the data-id of clicked image; how can I get it using my jQuery code.

Answer

Try this:

$(document).on('click', '.image1', function() {
   alert($(this).data("id"));
});
Comments