2

我有一个使用验证的表单。此表格有一个用于上传照片的部分。最初,本节包含六个元素,代码如下:

<img class="photo_upload" src="image/app/photo_upload.jpg">

我已经将一个函数绑定到photo_upload. 此函数使用以下代码将图像替换为最小形式:复制代码

<form onsubmit="startUploadImage();" target="control_target"
enctype="multipart/form-data" method="post" action="index.php">
<input type="hidden" value="add_image" name="service">
<input type="hidden" value="1000000" name="MAX_FILE_SIZE">
<input type="file" size="10" name="photo" id="photo_file_upload"><br>
<button onclick="javascript:cancel_photo_upload();return false;">Cancel</button>
</form>

因此,基本上,在单击图像后,我将在我的原始验证表单中嵌套一个新表单。现在,当我使用这个新表单并上传图片时,我收到一个错误(重复三遍)说:

validator is undefined
http://host.com/path/index.php
Line 286

这里发生了什么?我的猜测是这个

  1. 将事件气泡提交到外部表单
  2. 由于我们对该表单进行了验证,因此触发了验证,
  3. 验证试图找到触发它的表单,
  4. 由于我们没有将验证绑定到内部表单,因此它返回“未定义”

现在,我的评估是否正确?不管是不是,我该如何解决这个问题?

4

2 回答 2

2

HTML 中不允许嵌套表单。您需要使用带有两个提交按钮的单个表单并设置服务器端表单处理程序,以便它识别使用了哪个按钮并相应地分支。

于 2010-06-06T12:44:11.190 回答
2

如果您不想更改页面结构,可以通过修补事件处理函数来修复此错误delegate

jquery.validate.js v1.15.0,第 401 - 408 行:

function delegate( event ) {
    var validator = $.data( this.form, "validator" ),
        eventType = "on" + event.type.replace( /^validate/, "" ),
        settings = validator.settings;
    if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) {
        settings[ eventType ].call( validator, this, event );
    }
}

我的补丁版本:

function delegate( event ) {
    if (this.form === event.delegateTarget) {
        var validator = $.data( this.form, "validator" ),
            eventType = "on" + event.type.replace( /^validate/, "" ),
            settings = validator.settings;
        if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) {
            settings[ eventType ].call( validator, this, event );
        }
    }
}

修补缩小版本(jquery.validate.js 使用带有 uglify 的 grunt 打包分发)更难但并非不可能。function delegate(event)变成function b(b).

另一种方法是修补绑定时使用的选择器delegate。我认为这是一个更复杂的修复,但浏览器性能会稍微好一些。

于 2016-08-02T17:26:28.677 回答