使用jQuery显示图像

Display image using jQuery

本文关键字:图像 显示图 显示 jQuery 使用      更新时间:2023-09-26

当我拾取图像时,有时它不会显示,但当我第二次单击时,图像会显示。

jQuery

$('#morefiles').change(function (event) {
  if (!(/'.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) {
    $ionicPopup.alert({
      title: 'Message',
      template: 'You must select an image file only !'
    });
    $('#morefiles').val('');
  } else {
    var obj = {};
    obj.key = event.target.files[0];
    obj.value = URL.createObjectURL(event.target.files[0]);
    $scope.items.push(obj);
    console.log(JSON.stringify(obj));
    $('#morefiles').val(obj);
  }
});

HTML

<input type="file" multiple="" id="morefiles" accept="image/*" >

如何解决这个问题?当用户选择图像时,我需要显示当时的图像。提前谢谢。

好的。我抓住你了。。添加此行:

$scope.$apply();

到您的代码如下:

$('#morefiles').change(function (event) {
                if (!(/'.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) {
                    $ionicPopup.alert({
                        title: 'Message',
                        template: 'You must select an image file only !'
                    });
                    $('#morefiles').val('');
                } else {
                    var obj = {};
                    obj.key = event.target.files[0];
                    obj.value = URL.createObjectURL(event.target.files[0]);
                    $scope.items.push(obj);
                    $scope.$apply()
                    console.log(JSON.stringify(obj));
                    $('#morefiles').val(obj);
                }
            });

我也面临这个问题。但是通过这种方式解决了。我不知道为什么我需要做$scope.$apply();。我没有足够的时间去挖掘这些东西。如果有人知道原因,欢迎你评论我的回答。

试试这个:

$(function() {
  $('#morefiles').on('change', gotPic);
});
function gotPic(event) {
  if (event.target.files.length) {
    for (var i = 0; i < event.target.files.length; i++) {
      if (event.target.files[i].type.indexOf('image/') == 0) {
        var src = URL.createObjectURL(event.target.files[i])
        $('#preview').append('<img src = ' + src + '><br>');
      }
    }
  }
}
img {
  width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple="" accept="image/*;capture=camera" id="morefiles">
<br>
<div id="preview"></div>