I am using a File Upload script called Simple Photo Manager. When I upload a few images and I want to delete some of them, I have to create a variable numDeleted (number of images deleted)
I will describe the outcome and then I will show you the code.
Please le me know if you know why this is happening
The outcome is:
-Scenario: Three uploaded images are displayed
-I click 1st Delete, div is successfully hidden, then: alert('1')
-I click 2nd Delete, div is successfully hidden, then: alert('2'), alert('3')
-I click 3rd Delete, div is successfully hidden, then: alert('4'), alert('5'),alert('6')
This is the function that is exec when an image is uploaded:
function setUploadedImage(imgSrc, fileTempName, divId) {
var par = window.document;
var images = par.getElementById('images_container');
numDeleted = 0;
var imgdiv = par.getElementById(divId);
// all its attributes here...
var image_new = par.createElement('img');
// all its attributes here...
var image_label = par.createElement('input');
// all its attributes here...
var image_hidden = par.createElement('input');
// all its attributes here...
var image_name = par.createElement('input');
// all its attributes here...
var image_del_link = par.createElement('input');
// all its attributes here...
var br = par.createElement('br');
imgdiv.appendChild(image_new);
imgdiv.appendChild(image_hidden);
imgdiv.appendChild(image_name);
imgdiv.appendChild(br);
imgdiv.appendChild(image_del_link);
$(".deleteit").click(function(){
$(this).parent().hide();
numDeleted = numDeleted + 1;
alert(numDeleted);
})
Need to make some assumptions because of some missing information, but I assume the
image_del_linkelement has the'deleteit'class.If so, you’re binding new handlers to all elements in the DOM with that class. So every time a new one is set up, redundant handlers are added to the ones that already exist.
Change this…
to this…
…in order to bind only to the newly created element.
Or a better solution is to use event delegation with the
.on()method…This should be placed outside your
setUploadedImage()function so that it’s only run once.Any elements with the
.deleteitclass inside theimages_containerthat are clicked, will trigger the handler placed onimages_container.If you’re using an older version of jQuery, use
.delegate, instead of.on()…If you’re using a really old version, then upgrade.