如何阅读我的图像的url

How to read url of my image?

本文关键字:url 图像 我的 何阅读      更新时间:2023-09-26

我试图在我的脚本中设置src为动态附加的图像,用户首先浏览他的图像并在文本字段中输入他的名字,然后单击添加按钮,然后动态附加一个表行。

我想在其中显示图像。我的稿子有什么错误吗?

$(document).ready(function() {
  $('#addbtn').click(function() {
    var val = $.trim($('#txt-val').val());
    var some = $('#imagefile').val();
    if (val != '') {
      //$('#imagepath').attr('src','+some+');
      $("imagefile").change(function() {
        readURL('#imagefile');
      });
      $('#newval').append('<option>' + val + '</option>');
      $('#list-tbl').append('<tr height='"50'">' + '<td>' + val + '<img id='"imagepath'" src="#" style="width:50px; height:50px;"/>' + '</td>' + '<td>' + val + '</td>' + '</tr>');
    }
    $('#txt-val').val('');
  });
  function readURL(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
        $('#imagepath')
          .attr('src', e.target.result)
          .width(150)
          .height(200);
      };
      reader.readAsDataURL(input.files[0]);
    }
  }
});
.dynamictbl {
  width: 100%;
  height: auto;
}
table,
tr,
td {
  border: 1px solid #dddddd;
  border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="imagefile" onchange="readURL(this);" />
<input type="text" style="width:150px;" id="txt-val" />
<button id="addbtn">Add</button>
<select id="newval" style="width:150px;"></select>
<div style="width:100%; height:300px; margin-top:5px; overflow:auto;">
  <table id="list-tbl" class="dynamictbl">
    <tr height="50">
      <th width="50%">Index Of Entry<span id="img"></span>
      </th>
      <th width="50%">User Name</th>
    </tr>
  </table>
</div>

将readURL()函数置于jquery ready函数之外

readURL函数无法从click事件中访问,因此应该将其移动为可访问的。此外,readURL()应该在添加元素到DOM后调用,而不是在"onChange"事件时调用。

window.readURL = function(id) {
    var input = $('#imagefile')[0];
    if (input.files && input.files[0]) {
    var reader = new FileReader();
  reader.onload = function(e) {
    $('#'+id)
      .attr('src', e.target.result)
      .width(150)
      .height(200);
  };
    reader.readAsDataURL(input.files[0]);
  }
};
 $(document).ready(function() {
  var rows = 0;
   $('#addbtn').click(function() {
  var val = $.trim($('#txt-val').val());
  var some = $('#imagefile').val();
  if (val != '') {
    var id = 'imagepath' + (++rows);
    $('#newval').append('<option>' + val + '</option>');
    $('#list-tbl').append('<tr height='"50'">' + '<td>' + val + '<img id='"' + id + ''" src="#" style="width:50px; height:50px;"/>' + '</td>' + '<td>' + val + '</td>' + '</tr>');
    readURL(id);
  }
    $('#txt-val').val('');
   });
 });

工作示例:https://jsfiddle.net/4gyq1kvb/14/