【问题标题】:Not working "prepend" html5 image upload preview (dom)不工作“预先”html5图像上传预览(dom)
【发布时间】:2014-11-24 10:06:10
【问题描述】:

我有问题,当我使用 jquery 动态添加上传字段时:

$('.content div').prepend(
    '<div'
        + '<input type="file" id="fileselect" name="fileselect[]" multiple>'
        + '<div id="messages"></div>'
    + '</div>'
);

div #messages 显示图像预览和输入上传图像,在上传之前我可以在#messages 框中显示图像。

当我添加这个时:

<input type="file" id="fileselect" name="fileselect[]" multiple>
<div id="messages"></div>

在 html 中,一切正常,但 jquery 不起作用:( 我在上传脚本之前使用这个 html5 节目:http://blogs.sitepointstatic.com/examples/tech/filedrag/2/index.html http://blogs.sitepointstatic.com/examples/tech/filedrag/2/filedrag.js

如何编辑此插件以使用 dom ?

【问题讨论】:

  • 您需要将addEventListener 调用添加到新创建的元素中,或者使用委托事件。
  • 你的文件上传概念在哪里?我们需要代码
  • 我现在不上传图片,我要创建图片预览;)
  • @RoryMcCrossan 我如何添加这个? ://

标签: jquery html dom upload preview


【解决方案1】:

更新:主要问题是在文件输入字段在 DOM 中准备好之前加载了 filedrag.js 脚本。一旦脚本被异步加载,随后的调用就会起作用。

试试这个:

$("#fileselect").change(function() {
  var imgStr = "<img src='"+$(this).val()+"'/>";
  $("#messages").html(imgStr);
});

【讨论】:

  • 我可以在哪里使用它?这个插件使用纯js
  • 在你的prepend() 语句结束后调用这个函数。
  • 不起作用,在控制台返回:未捕获的类型错误:无法读取 null 的属性 'addEventListener' 不允许加载本地资源:file:///C:/fakepath/wallpaper.jpg
  • 如果您注意到错误,它会将文件名解释为C:/fakepath/wallpaper.jpg。在函数内你可以尝试做imgStr = imgStr.replace('/fakepath','');
  • 不,/fakepath 这是我的路径,jquery 自动生成此消息,因为此方法不允许打开图像。我必须调试这个:Uncaught TypeError: Cannot read property 'addEventListener' of null
猜你喜欢
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-12
  • 2023-04-01
  • 1970-01-01
  • 2011-05-26
相关资源
最近更新 更多