Javascript将数据插入表单';s输入';s-用数据填充表单

Javascript将数据插入表单';s输入';s-用数据填充表单,javascript,forms,input,get,Javascript,Forms,Input,Get,用javascript填充表单最快的“性能”方式是什么 我有这个和它的工作,但我在想有更好或更快的方法来做吗 async function PopulateUpdateForm(formID) { var currentForm = document.getElementById(formID); // Get the form var resPrommise = await GetUserData(); // Get responce // Popul

用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']; 
         }
    
    });
}
异步函数PopulateUpdateForm(formID)
{
var currentForm=document.getElementById(formID);//获取表单
var respromise=wait GetUserData();//Get responce
//填充表单
等待respromise.json()。然后(content=>//获取响应内容
{
if(content==null)返回;
['email','firstname','lastname','phonenumber'].foreach(x=>
currentForm[x]。值=内容[x];
)
如果(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)

谢谢你的回答,这会更快吗?它的优点是什么?打字更快,但跑起来不快。优点是它更简洁/易读谢谢你的回答-我只使用vanilla js。谢谢,但这比手动设置有更好的性能吗?就我个人而言,我在最近的项目中使用了这项技术,我注意到它比手动快了一点(我之前遵循过)。比如在使用modal进行编辑时,我的表单中有很多字段,渲染需要一些时间,有时我注意到很少的延迟(毫秒)并不总是明显的。所以,我个人喜欢这种方法。你一定要试试这个。。