2013-08-02 4 views
2
$('.image-remove').click(function() { 

ЭТОТ КОД ПОВТОРЯЕТСЯ ДВАЖДЫ Когда я нажимаю на .image-удалить Я понятия не имею, почему!нажмите событие повторив (JQuery 1.9)

$(function() { 
var uploader = new plupload.Uploader({ 
    runtimes : 'html5,flash,html4', // Runtimes in order of priority. If browser does not have HTML5, it will load flash. 
    browse_button : 'agregarArchivo', // Button to select files 
    max_file_size : '300mb', 
    dragdrop: true, 
    drop_element : 'agregarArchivo', 
    url : 'tempupload.php', // PHP file that the images will be sent to server side 
    resize : {width : 400, quality : 60}, // File resize BEFORE it is sent to PHP url 
    unique_names:true, 
    flash_swf_url : 'js/plupload/plupload.flash.swf', // Required file if flash runtime is used 
    filters : [ 
     {title : "Image files", extensions : "jpg,gif,png"}, // Ensure that only images are loaded 
    ], 
}); 

var listaArchivos = new Array(); 
var cantidadArchivos = 0; 
var anchoThumbnail=129; //Incluyendo margenes 
var maxFiles=6; 
// Initialize Plupload 
uploader.init(); 

uploader.bind('FilesAdded', function(up, files) { 

    if((cantidadArchivos + files.length) > maxFiles) 
    { 
      // Removing the extra files 
      while(up.files.length > maxFiles) 
       { 
        if(up.files.length > maxFiles) 
        uploader.removeFile(up.files[maxFiles]); 
       } 
      alert('Solo puedes subir 6 fotos'); 
      //uploader.splice(); // reset the queue to zero 
     } 
    else 
     { 
      // Go over each file to make sure it is the correct size 
      $.each(files, function(i, file) { 
       if (file.size > 3*10485759) // If file size is over 30 mb 
        { 
         // Create an image shadow notifying the user of the error 
         $('#upload-dump').append('<div class="image-error"></br>Error: El archivo es demasiado grande (Max 30 MB)</br>' + file.name + '</div>'); 
         alert('Error: El archivo es demasiado grande, Max 10 MB'); 
         uploader.splice(i,1); 
        } 
       else // If the file is under 10mb 
        { 
         cantidadArchivos++;   
         //Se reduce el tama�o de #agragarArchivo cada vez que una foto se agrega. 
         $('#agregarArchivo').css('width',((maxFiles-cantidadArchivos) *anchoThumbnail) -4 + 'px'); 

         //Si ya se han agregado 4 o m�s fotos, se achica el tama�o de letra y el tama�o de #agregarArchivo 
         if(cantidadArchivos == 4){ 
           $('#agregarArchivo').css('font-size','18px'); 
           $('#agregarArchivo').html('Click para agregar fotos'); 
         } 
         if(cantidadArchivos == 5){ 
           $('#agregarArchivo').css('font-size','16px'); 
           $('#agregarArchivo').html('Agregar fotos'); 
         } 
         if(cantidadArchivos == 6){ 
           $('#agregarArchivo').hide(); 
         } 


         // Create an image shadow set at 0 percent 
         $('#upload-dump').append('<div id="' + file.id + '" class="image-shadow">0%</div>'); 

         //Rename the uploaded file! 
         var regex = /(?:\.([^.]+))?$/; 
         var ext = regex.exec(uploader.files[i].name)[1]; 
         uploader.files[i].name = (ext == undefined) ? (i+1) : (i+1) + '.' + ext; 


        } 
      }); 
      up.start(); 

     } 
}); 

// Maintain progress of the image upload 
uploader.bind('UploadProgress', function(up, file) { 
    $('#' + file.id).html(file.percent + '%'); 
}); 

// Notify user of any errors 
uploader.bind('Error', function(up, err) { 
    $('#runtime').html('<div> ' + err.message + ':' + err.file.name + '</div>');          
}); 

// Do this when each file is uploaded.           
uploader.bind('FileUploaded', function(up, file, response) { 
    // Change the progress to 100% 
    $('#' + file.id).html('100%'); 
    // Replace the image shadow with the actual thumbnail image 
    $('#' + file.id).replaceWith('<div id="' + file.id + '" class="image-picture"><img src="tempthumb/' + jQuery.parseJSON(response.response).result + '" /><div title="Quitar Imagen" class="image-remove"></div> </div> <input type="hidden" id="' + file.id + '" name="' + jQuery.parseJSON(response.response).result +'" value="SI"/> '); 
    //Agregar un campo "input" oculto, que se usar� para pasar los nombres de las imagenes al script PHP. 

// $ ('#' + jQuery.parseJSON (response.response) .result) .insertAfter (''); });

// Do this when all files are uploaded 
uploader.bind('UploadComplete', function(up, files) { 

    // Allow the user to remove the picture if it's incorrect 
    $('.image-remove').click(function() { 
     //Quito un archivo del contador.    
     cantidadArchivos--;   

     //Marco el "input" correspondiente a la foto que se elimina, con el valor NO. Este valor se usar� posteriormente en el php que procesa el envio del formulario. 
     //Obtengo el id de la foto que se borrar�. 
     idborrado=$(this).parent().attr('id'); 
     //Borro el div donde se encuentra la imagen 
     $(this).parent().remove(); 
     //Ahora que NO hay duplicidad de ID, cambio el valor del input a "NO", que significa que NO se debe considerar esa imagen. No puede ser en otro orden. 
     $('#' + idborrado).val('NO'); 

     //Agrando el tama�o del div #agregarArchivo, y modifico el tama�o de letra de acuerdo a las fotos agregadas. 
     if(cantidadArchivos <= 3){ 
       $('#agregarArchivo').css('width',((maxFiles-cantidadArchivos) *anchoThumbnail) -4 + 'px'); 
       $('#agregarArchivo').css('font-size','30px'); 
       $('#agregarArchivo').html('Click para agregar fotos'); 
     } 
     if(cantidadArchivos == 4){ 
       $('#agregarArchivo').css('width',((maxFiles-cantidadArchivos) *anchoThumbnail) -4 + 'px'); 
       $('#agregarArchivo').css('font-size','18px'); 
       $('#agregarArchivo').html('Click para agregar fotos'); 
     } 
     if(cantidadArchivos == 5){ 
       $('#agregarArchivo').show(); 
       $('#agregarArchivo').css('width',((maxFiles-cantidadArchivos) *anchoThumbnail) -4 + 'px'); 
       $('#agregarArchivo').css('font-size','16px'); 
       $('#agregarArchivo').html('Agregar fotos'); 
     } 
    }); 

}); 
}); 
/* El script NO borra los thumbnails que se crean, por lo que hay que borrarlos manualmente */ 

ответ

0

Это должно быть как

$('.image-remove').click(function() { 
    var uploader = new plupload.Uploader({ 
    runtimes : 'html5,flash,html4', // Runtimes in order of priority. If browser does not have HTML5, it will load flash. 
    browse_button : 'agregarArchivo', // Button to select files 
    max_file_size : '300mb', 

Dont поставить код под ниже, пока речь идет под событием.

$(function(){....}) 

Он будет работать скрипт во время загрузки страницы

4

я решил его с помощью следующего кода:

$('.image-remove').unbind('click').click(function() { 

По какой-то причине, что я не понимаю щелчок (функция() пожары в два раза, когда вы динамически создать DIV

Вот объяснение проблемы:. http://webroxtar.com/2011/10/solution-jquery-click-event-gets-called-twice-fires-twice/

+0

+1 для ссылки – 5hahiL

0

Это происходит потому, что, когда вы перезагружаете контент, в котором есть скрипт, который добавляет событие клика, вы фактически связываете события кликов, дважды или более, зависит от того, сколько раз вы загружаете этот контент. Поэтому вы должны использовать unbind («click»), чтобы удалить ранее добавленные связующие.

Смежные вопросы