在 JavaScript 中扩展或覆盖函数
Extending or overriding a function in JavaScript
我们在 JavaScript 中有一个关于表单绑定的函数,类似于
var formBind = function( event ) {
event.preventDefault();
var form = $(this);
// some ajax post and validation portion here
return false;
};
formBind 在许多页面上用作$('form:visible').submit(formBind);
现在我要求在提交之前只在特定页面上应用额外的确认框。如何在对原始代码进行最少更改的情况下添加该功能?
将原始表单嵌套在新函数中绑定
var formBind = function( event ) {
event.preventDefault();
var form = $(this);
// some ajax post and validation portion here
return false;
};
var additionalFormBind = function( event ) {
var result = null;
// do additional work before original formBind
result = formBind( event );
// do additional work after original formBind
return result;
}
$('form:visible').submit(additionalFormBind);
您可以使用 jQuery 的数据参数来传递额外的信息。
$('form:visible').submit({ showConfirm: true }, formBind);
然后签入处理程序:
var formBind = function( event ) {
event.preventDefault();
var form = $(this);
if(event.data.showConfirm) {
// confirmation code goes here.
}
// some ajax post and validation portion here
return false;
};
在 JavaScript 中,您可以向函数调用或定义添加任意数量的参数 - 仅使用提供或匹配的参数。 您可以像这样更改函数:
var formBind = function( event, showConfirm ) {
event.preventDefault();
var form = $(this);
if (showConfirm) {
//logic to display confirmation, followed by a call to the original ajax post if required
} else {
// some ajax post and validation portion here
}
return false;
};
调用此函数的所有现有位置都不会提供此参数,因此它将未定义,并且if
将计算为false
并保持原始功能不变。 在新代码中,您可以根据需要true
或false
提供它:
$('form:visible').submit(function(e) { return formBind(e, true); });
用包含确认的新函数包装formsubmit
函数。
$('form:visible').submit(confirmAndSubmit);
var confirmAndSubmit = function( event ) {
event.preventDefault();
return (window.confirm("Are You Sure?"))?formsubmit(event):false;
};
相关文章:
- 覆盖函数中的函数
- 如何在javascript中覆盖函数的行为
- Javascript闭包覆盖函数表达式
- 具有生成名称的 Javascript 覆盖函数
- 在节点导出中覆盖函数的 toString()
- for 循环中的覆盖函数
- 在 JavaScript 中扩展或覆盖函数
- 覆盖函数(例如“alert”)并调用原始函数
- Javascript覆盖函数
- 如何在javascript中使用原型覆盖函数
- 覆盖/覆盖函数内部的函数
- JavaScript - 使用包含异步回调但仍返回原始值的函数覆盖函数
- Javascript 闭包 - 全局范围内被覆盖函数的行为
- 如何在javascript中用可变数量的参数覆盖函数
- 如果a或b = null或无值,则…填充最后一个字段将覆盖函数
- 保持添加值而不覆盖函数
- JS模块模式覆盖函数
- Javascript模块-覆盖函数
- 覆盖函数以识别任何dom更改,包括像jquery这样的插件
- 来自dataTableExt.oApi的数据表覆盖函数