什么是最快的-"性能";用javascript填充表单的方法。
我有这种方法,但我在想,有更好或更快的方法吗?
async function PopulateUpdateForm(formID)
{
var currentForm = document.getElementById(formID); // Get the form
var resPrommise = await GetUserData(); // Get responce
// Populate the Form
await resPrommise.json().then(content => // Get the response content
{
if (content != null)
{
currentForm['email'].value = content['email'];
currentForm['firstname'].value = content['firstname'];
currentForm['lastname'].value = content['lastname'];
if (content['age'] != 0)
{
currentForm['age'].value = content['age'];
}
currentForm['phonenumber'].value = content['phonenumber'];
}
});
}
async function PopulateUpdateForm(formID)
{
var currentForm = document.getElementById(formID); // Get the form
var resPrommise = await GetUserData(); // Get responce
// Populate the Form
await resPrommise.json().then(content => // Get the response content
{
if (content == null) return;
['email', 'firstname', 'lastname', 'phonenumber'].forEeach(x =>
currentForm[x].value = content[x];
)
if (content['age'] != 0) currentForm['age'].value = content['age'];
});
}
为了可读性,我会保留您填充表单的方式,除非您使用React或Vue这样的被动框架。
有更好的方法。您不必手动设置值,而是可以动态地进行设置。。。
使用这个:
function PopulateUpdateForm(currentForm, data) {
$.each(data, function(key, value) {
// Populate Form data by input Name
var ctrl = $('[name='+key+']', currentForm);
switch(ctrl.prop("type")) {
case "radio": case "checkbox":
ctrl.each(function() {
if($(this).attr('value') == value) $(this).attr("checked",value);
});
break;
default:
ctrl.val(value);
}
});
}
并通过调用使用
var currentForm = document.getElementById(formID); // Get the form
var data = GetUserData(); // Get responce data
PopulateUpdateForm(currentForm, data)