<input type =“file”/>的jQuery更改事件通过删除标签上的文件而不起作用

时间:2018-01-18 01:08:46

标签: javascript jquery input file-upload

我正在努力工作。 drop file uploader,可以通过单击标签或删除标签上的文件来触发。

输入字段有一个jQuery on change事件,该事件在选择文件时触发。但它仅在通过资源管理器菜单选择文件时有效,但不适用于拖放事件。为什么呢?

&#13;
&#13;
$(document).ready(function() {	
  $('label').on('drag dragstart dragend dragover dragenter dragleave drop', function(event) {
    event.preventDefault();
    event.stopPropagation();
  })
  .on('dragover dragenter', function() {
    $(this).addClass('is-dragover');
  })
  .on('dragleave dragend drop', function() {
    $(this).removeClass('is-dragover');
  })
  .on('drop', function(event) {			
    // Set file on drop
    $('input[type=file]').prop('files', event.originalEvent.dataTransfer.files);      
  });

  // Check if change event works
    $('input[type=file]').on('change', function(event) {    
    $('#result span').text(event.target.files[0].name);      
  });

});
&#13;
input {
  display: block;
  margin-bottom: 10px;
}

label {
  padding: 20px;
  
  display: inline-block;
  
  border: 2px dashed grey;
}

label:hover {
 background: lightgray;
 cursor: pointer;
}

label.is-dragover {
  background: grey;
}

#result {
  margin-top: 10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" id="file-field" name="file-field">
<label for="file-field">Click to select (works)<br>Drop file (doesn't work)</label>

<div id="result">
File on change event: <span></span>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您可以触发change事件: $('input[type=file]').trigger('change');

$(document).ready(function() {	
   $('label').on('drag dragstart dragend dragover dragenter dragleave drop', function(event) {
			event.preventDefault();
			event.stopPropagation();
		})
		.on('dragover dragenter', function() {
			$(this).addClass('is-dragover');
		})
		.on('dragleave dragend drop', function() {
			$(this).removeClass('is-dragover');
		})
		.on('drop', function(event) {
			
      // No idea if this is the right way to do things
			$('input[type=file]').prop('files', event.originalEvent.dataTransfer.files);
           $('input[type=file]').trigger('change');
		});
    
    $('input[type=file]').on('change', function(event) {
    
      $('#result span').text(event.target.files[0].name);
      
    });
    
});
input {
  display: block;
  margin-bottom: 10px;
}

label {
  padding: 20px;
  
  display: inline-block;
  
  border: 2px dashed grey;
}

label:hover {
 background: lightgray;
 cursor: pointer;
}

label.is-dragover {
  background: grey;
}

#result {
  margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" id="file-field" name="file-field">
<label for="file-field">Click to select (works)<br>Drop file (doesn't work)</label>

<div id="result">
File on change event: <span></span>
</div>