【问题标题】:How can I change the label name when file is selected?选择文件时如何更改标签名称?
【发布时间】:2022-01-03 21:29:38
【问题描述】:

HTML 如下-

<input type="file" class="custom-file-input" accept="image/*" onchange="loadFile(event)" id="customFile">
 <label class="custom-file-label" id="change" for="customFile">Choose File</label><br><br>
 <img width="150px" id="output" src="#"/>

脚本如下-

var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
    URL.revokeObjectURL(output.src) // free memory
}
};

我的代码能够显示所选图像,但我也想将标签文本更改为所选图像名称

【问题讨论】:

    标签: javascript html jquery image file-upload


    【解决方案1】:

    更改标签文本的逻辑可以写在更改事件上。检查以下事件sn -p,

    document.getElementById('customFile').onchange = function() {
      // code to change the label text
      var fullName = getFileName(document.getElementById('customFile').value);
      document.getElementById("change").innerHTML= fullName;
    };
    var getFileName = function(fullPath) {
      if (!fullPath) return null;
      var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
      var filename = fullPath.substring(startIndex);
      if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        return filename.substring(1);
      }
      return null;
    }
    

    有关获取文件名的更多信息,请查看https://stackoverflow.com/a/857662/17542117

    【讨论】:

    • 感谢它现在可以使用。
    【解决方案2】:
    Var name = document.getElementById("customFile").value;
    

    使用

    document.getElementById("Change").innerHTML = name
    

    请更正拼写。

    【讨论】:

    • 我知道这么多,但是我怎样才能得到图像名称以及在 = 之后给出什么,你能告诉我吗?
    • 看看我已经编辑了评论
    猜你喜欢
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 2020-05-05
    • 2017-01-12
    • 2011-07-14
    • 1970-01-01
    相关资源
    最近更新 更多