我在一页上有多个表单,我正在使用 jQueryForm plugin无需重新加载页面即可处理它们。问题是,我需要一些视觉响应来判断表单提交是否有效,所以我将边框从灰色更改为绿色(如果有效),如果无效则更改为红色。
好吧,这适用于纯 jQuery,但不适用于此插件,因为当我使用 $(this)
时,它指的是函数本身。
有人知道怎么做吗?
var edit_form = {
dataType: 'json',
success: function(output) {
console.log($(this));
$form = $(this);
$form.css("border-color", "green");
setTimeout(function(){
$form.css("border-color", "#323131");
}, 3000);
},
error: function(output) {
console.log($(this));
$form = $(this);
$form.css("border-color", "red");
setTimeout(function(){
$form.css("border-color", "#323131");
}, 3000);
}
};
$('.twitch-form').ajaxForm(edit_form);
控制台日志返回:
[Object, constructor: function, init: function, selector: "", jquery: "1.7.2", size: function…]
通常情况下,我会使用 $.post
但我需要能够使用这些表单上传图片...
谢谢。
最佳答案
如果您查看 plugin documentation (看success
选项),success方法获取表单对象作为第4个参数
success
Callback function to be invoked after the form has been submitted. If a 'success' callback function is provided it is invoked after the response has been returned from the server. It is passed the following arguments: 1.) responseText or responseXML value (depending on the value of the dataType option). 2.) statusText 3.) xhr (or the jQuery-wrapped form element if using jQuery < 1.4) 4.) jQuery-wrapped form element (or undefined if using jQuery < 1.4)
所以
var edit_form = {
url: 'asdf/asdf',
dataType: 'json',
success: function (output, status, xhr, $form) {
console.log('x',$form, status);
$form.css("border-color", "green");
setTimeout(function () {
$form.css("border-color", "#323131");
}, 3000);
},
error: function (xhr, status, error, $form) {
console.log($form)
$form.css("border-color", "red");
setTimeout(function () {
$form.css("border-color", "#323131");
}, 3000);
}
};
$('.twitch-form').ajaxForm(edit_form);
演示:Fiddle
关于javascript - 提交时的 jQuery 表单(插件)用表单做一些事情 -> $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29761898/