简体   繁体   中英

click event not working jQuery

I am trying to handle the click event using jQuery

on upload success, I am creating the following using jQuery:

$("#uploadedImage").append( "<div class='img-wrap'>
    <span class='deletePhoto'>&times;</span>
    <img data-id='"+files[i]+"' src='"+asset_url+"uploads/ad_photo/"+files[i]+"'>
  </div>
  <span class='gap'></span>");

and for handling click event for the above created div's I have written this:

$('.img-wrap .deletePhoto').click(function() {
  var id = $(this).closest('.img-wrap').find('img').data('id');
  alert(id);
});

the above code is working properly and creates all div, but when I click on the deletePhoto span. no jQuery alert is showing.

Any help or suggestion would be a great help.

Thanks in advance

delegate the event and change as suggested:

$("#uploadedImage").on('click', '.deletePhoto', function() {

You have to delegate your event to the closest static parent #uploadedImage in your case which is available on the page load like the container which holds the newly appended div and image.

although $(document) and $(document.body) are always available to delegate the event.

It is better to use on() when you create new element after DOM has been loaded.

$(document).on('click', '.img-wrap .deletePhoto', function() {

});

You are creating your element dynamically that is why you would need .live() but this method is deprecated in newer version. if you want to use jquery 1.10 or above you need to call your actions in this way:

$(document).on('click','element',function(){
  `your code goes in here`
})

try this:

$(".img-wrap .deletePhoto").on('click', function() {

});

First check in debugging mode that you get length when your code is going to bind click event and another thing bind event must written after that element is appended.

And Also check css of your element (height and width) on which you are clicking and yes

$(document).on('click','Your Element',function(){
  //your code goes in here
});

Will works fine

use delegate :

$('#uploadedImage').on('click','.img-wrap .deletePhoto',function() {
  var id = $(this).closest('.img-wrap').find('img').data('id');
  alert(id);
});

see details delegate and .on here

You can change a little in your code.

$(".deletePhoto").off("click").on("click",function(){
  //Your Code here
});

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