【问题标题】:Javascript insert data into form's input's - Populate form with dataJavascript将数据插入表单的输入 - 用数据填充表单
【发布时间】:2021-05-11 13:38:33
【问题描述】:

在 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']; 
         }
    
    });
}

【问题讨论】:

    标签: javascript forms input get


    【解决方案1】:

    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'];
      
        });
    }

    【讨论】:

    • 感谢您的回答,这样会更快吗?优点是什么?
    • 输入速度更快,但运行速度不快。优点是它更简洁/可读
    【解决方案2】:

    为了可读性,我会保留你填充表单的方式,除非你使用像 React 或 Vue 这样的响应式框架。

    【讨论】:

    • 感谢您的回答 - 我只使用 vanilla js。
    【解决方案3】:

    有更好的方法来做到这一点。您不必手动设置值,而是可以动态设置...

    使用这个:

    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)
    

    【讨论】:

    • 谢谢,但是这比手动设置有更好的性能吗?
    • 就我个人而言,我在最近的项目中使用了这种技术,我注意到它比手动(我之前遵循的)快一点。就像使用模态进行编辑时,我的表单中有很多字段需要一些时间来渲染,有时我注意到一点延迟(毫秒)并不总是很明显。
    • 所以,我个人喜欢这种方法。你一定要试试这个..
    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 2021-06-04
    • 2018-03-08
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多