我有一个包含大约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),即使用户没有使用展开/折叠或日期选择器,所有这些视频都会在表单中使用下拉列表显着减速。所以我期待我们在自动保存例程中导致锁定或内存泄漏。
对于重构的建议将不胜感激。
答案 0 :(得分:0)
以上评论很棒,我建议按照@Adam和@Alex发布的建议(改为通过命名函数)。此外,您可能尝试以不同的方式实现(即模块设计模式或其他一些最佳实践)。看看这个StackOverflow问题:https://stackoverflow.com/questions/4840420/recommended-javascript-annotated-source-code-for-learning