一个类的多个事件侦听器

时间:2016-06-24 02:48:01

标签: javascript jquery drag-and-drop event-listener

我正在尝试制作多个拖放区域。我正在尝试添加一个" drop-zone" class(对于具有此类的每个元素)。

var dropZone = document.getElementById('some_area'); // ok
// var dropZone = document.getElementByClassName('drop-zone'); // not working

dropZone.addEventListener('dragover', function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer.dropEffect = 'copy';
});

dropZone.addEventListener('drop', function(e) {
    var target_img = $(this).find('img');
    e.stopPropagation();
    e.preventDefault();
    var files = e.dataTransfer.files; // Array of all files
    for (var i=0, file; file=files[i]; i++) {
        if (file.type.match(/image.*/)) {
            var reader = new FileReader();
            reader.onload = function(e2) { // finished reading file data.
                var img = document.createElement('img');
                img.src= e2.target.result;
                target_img.attr('src',e2.target.result);
                target_img.addClass('full-preview');
            }
            reader.readAsDataURL(file); // start reading the file data.
}   }   });

1 个答案:

答案 0 :(得分:2)

您需要查询具有特定类的所有元素。

// Returns a list of the elements within the document 
// that match the specified 'drop-zone' class.   
var dropZones = document.querySelectorAll('.drop-zone');


for (var i = 0; i < dropZones.length; i++) {
  // Add the event listeners for each element of the list.
  dropZones[i].addEventListener('dragover', function (e) {
    // ...
  });

 dropZones[i].addEventListener('drop', function (e) {
   // ...
 });
}