2

目前我正在创建一个单页上传器。我用 Javascript (+jQuery) 开发并使用AppJS

此上传器有 2 个表单,其中上传输入可用。两个表格都在一页中,第二个表格被隐藏display: none;

两者都使用相同的定制上传扩展。

  • 在第一种形式中,我要求 2 张图片,它们必须被丢弃。

  • 当我删除图像时,它会通过套接字上传到我的 nodejs 服务器并正确保存。

  • 当我再次删除第二个时,它会上传到我的 nodejs 服务器并正确保存。

  • 然后我将表单发布到我的 nodejs 服务器

  • 之后我.hide()第一个表格和.show()第二个表格。

当我再次使用上传插件时,没有出现错误,但也没有上传文件。

我注意到 FileReader.onload 在第一个表单发布后没有执行。

在一些示例代码下面,我无法发布我的整个应用程序。

HTML

<form id="formone" action="/formone">
    <input type="text" name="background" value="Drop here" class="uploadinput" readonly />
    <input type="text" name="logo" value="Drop here" class="uploadinput" readonly />
</form>
<form id="formtwo" action="/formtwo" style="display:none;">
    <input type="text" name="icon" value="Drop here" class="uploadinput" readonly />
</form>

Javascript

// File upload extension
$.fn.extend({
    filedrop: function() {
        return this.each(function() {
            var files = []
            var $this = $(this)

            // Catch drop event
            $this.bind('drop', function(event) {
                event.stopPropagation()
                event.preventDefault()

                console.log('Dropped') // Works in both forms

                files = event.originalEvent.target.files || event.originalEvent.dataTransfer.files

                file = files[0]

                var reader = new FileReader()

                // reader.onload only works in form 1
                reader.onload = function(e) {
                    var buffer = e.target.result
                    socket.emit('uploadfile', file.name, buffer)
                }

                reader.onerror = function(error) {
                    console.log("error", error)
                    console.log(error.getMessage())
                }

                reader.readAsBinaryString(file)

                return false
            })
        })
    }
})

$('.uploadinput').filedrop()

window.showFormTwo = function() {
    $('#formone').hide()
    $('#formtwo').show()
}

节点.js

app.router.post('/formone', function() {
    window.showFormTwo()
})
4

1 回答 1

0

javascript加载后立即调用函数filedrop,但您的form2随后被隐藏。从绑定API :

处理程序附加到 jQuery 对象中当前选定的元素,因此这些元素必须存在于调用 .bind() 的位置。有关更灵活的事件绑定,请参阅 .on() 或 .delegate() 中有关事件委托的讨论。

所以因为 form2 是隐藏的,所以永远不会绑定 drop 事件,并且永远不会调用它的事件处理程序。reader.onload 在此事件处理程序中。.on是将事件处理函数附加到元素的首选方式。

所以改变这个

$this.bind('drop', function(event) {

$this.on('drop', function(event) {
于 2013-03-26T17:57:57.797 回答