我有一个包含大约 105 个字段的 html 表单,其中包括一些 javascript 事件:
1) 展开/折叠部分
http://www.adipalaz.com/experiments/jquery/nested_accordion.html
2)日期选择器
3) 自动保存功能
<script type="text/javascript">
function counter() {
email = document.getElementById("applicant-email").value;
if (email.match(emregex) || cd == cdLength){
if (email.match(emregex)){
document.getElementById("countdown").innerHTML = left + cd-- + right + button;
if (cd < 0){
formAutosave();
}
}else{
document.getElementById("countdown").innerHTML = "Enter your email address for AutoSave <a onclick=\"javascript:alert(\'Please enter an email address\');\"><span><b></b>Save Now</span></a>";
}
}
};
function formAutosave() {
window.clearInterval(timer);
email = document.getElementById("applicant-email").value;
if (email.match(emregex)){
document.getElementById("countdown").innerHTML = \'<a><span><b></b>Saving ...</span></a>\';
var values = "";
for (var i = 0; i < userForm.length; i++) {
if (userForm.elements[i].value != null) {
if (userForm.elements[i].name == "form[autosave]") {
userForm.elements[i].value = "TRUE";
}
if (userForm.elements[i].id == "'.$fieldId.'"){
userForm.elements[i].value = email;
}
if (userForm.elements[i].id != "finished"){
values += userForm.elements[i].name + "=" + encodeURI(userForm.elements[i].value) + "&";
}
}
}
values = values.substring(0, values.length - 1);
jQuery.post(
"http://'.$_SERVER['SERVER_NAME'].
$uri.strstr($uri,'?')?'&':'?').'autosave=1&format=raw",
values,
function (submissionId){
if (parseInt(submissionId) > 0){
jQuery("#continue").val(parseInt(submissionId));
}
cd = cdLength;
timer = window.setInterval("counter()", 1000);
}
);
};
};
var userForm = document.getElementById("userForm");
var emregex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
cdLength = '.self::SAVEINTERVAL.';
var left = \'Automatically saving in \';
var cd = cdLength;
var right = \' seconds or \';
var button = \'<a onclick="javascript: formAutosave();"><span><b></b>Save Now</span></a>\';
jQuery("#applicant-email").val(jQuery("#'.$fieldId.'").val());
var timer = window.setInterval("counter()", 1000);
';
我们录制了 3 个测试视频(Chrome、Firefox、IE9),在所有视频中,即使用户没有使用展开/折叠或日期选择器,使用表单中的下拉菜单也会明显减慢速度。所以我预计我们会在自动保存例程中导致锁定或内存泄漏。
有关重构的建议将不胜感激。
最佳答案
上面的评论很棒,我建议遵循 @Adam 和 @Alex 发布的建议(改为传递命名函数)。另外,您可以尝试以不同的方式实现(即模块设计模式或其他一些最佳实践)。看看这个 StackOverflow 问题:https://stackoverflow.com/questions/4840420/recommended-javascript-annotated-source-code-for-learning
关于javascript - 大表单或 javascript 锁定浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8934593/