HTML:
<input name="fileToUpload" type="file" id="fileToUpload"/>
<div id="div1"> </div>
Run Code Online (Sandbox Code Playgroud)
查询:
$(function()
{
$("#fileToUpload").on('change', 'input' , function(){
// Display image on the page for viewing
readURL(this,"div1");
});
});
function readURL(input , tar) {
if (input.files && input.files[0]) { // got sth
// Clear image container
$("#" + tar ).empty();
$.each(input.files , function(index,ff) // loop each image
{
var reader = new FileReader();
// Put image in created image tags
reader.onload = function (e) {
$('#' + tar).attr('src', e.target.result);
}
reader.readAsDataURL(ff);
});
}
Run Code Online (Sandbox Code Playgroud)
我想显示上传到 div 容器的图像,但是我的代码不起作用。知道如何使它工作吗?
问题是,你是
$("#fileToUpload").on('change', 'input' , function(){
变成
$("#fileToUpload").on('change', function(){
你的 div 变成了一个 img。
完整解决方案:
<input name="fileToUpload" type="file" id="fileToUpload"/>
<img id="preview" />
Run Code Online (Sandbox Code Playgroud)
$(function() {
$("#fileToUpload").on('change', function() {
// Display image on the page for viewing
readURL(this, "preview");
});
});
function readURL(input, tar) {
if (input.files && input.files[0]) { // got sth
// Clear image container
$("#" + tar).removeAttr('src');
$.each(input.files, function(index, ff) // loop each image
{
var reader = new FileReader();
// Put image in created image tags
reader.onload = function(e) {
$('#' + tar).attr('src', e.target.result);
}
reader.readAsDataURL(ff);
});
}
}
Run Code Online (Sandbox Code Playgroud)
工作小提琴:https : //jsfiddle.net/u7ww6bwv/