动态创建文件输入的最佳方法

时间:2019-06-12 06:21:41

标签: javascript html

我有一些自定义上传文件选项,例如多个超链接。单击该按钮时,我需要触发隐藏文件输入。说,我有10个超链接可以上传不同的图标。
有两种方法可以做到:
1.创建10个文件输入并隐藏它们,并在单击相应的超链接时手动触发它们。
2.为此创建一个通用函数,当用户单击超链接时,在该函数中,使用javascript创建文件输入并使用js触发它。

所以,我的问题是哪个是最好的,或者有一种有效的方法做到这一点。

2 个答案:

答案 0 :(得分:4)

您可以尝试通过创建单个input type='file'并使用accept属性来限制accepted file types

<input type="file" id="profile_pic" name="profile_pic"
          accept=".jpg, .jpeg, .png">

答案 1 :(得分:0)

在javascript中,您可以使用createElement函数创建输入字段.createElement(),然后将带有.appendChild()的元素附加到所需的位置。

因此,您可能可以创建一个函数来创建适当的输入字段:

function appendInput(inputType){
    if(inputType==1){
      var input = document.createElement("input");
      input.setAttribute('type', 'file');
      $('body').appendChild(input);//just replace body with whatever element you want to append the input to e.g $('#someDivId').appendChild(input);
    }else if(inputType==2){
      //some other input
    }/...
  }

但是,如果您只是尝试输入不同类型的文件,那么brk的答案会更加有效

希望有帮助

编辑从维护的角度来看,隐藏和显示10个不同的输入字段也有些不好,因此我建议根据所单击的超链接创建不同的输入字段。

根据我的阅读,

EDIT2 ,您需要每个输入都具有不同的名称,因此您只需将功能更改为:

function(inputName){
    var input = document.createElement("input");
    input.setAttribute('type', 'file');
    input.setAttribute('name', inputName);//pass the name of each input field
    $('body').appendChild(input);
}
相关问题