繁体   English   中英

如何<label>使用文件名</label>更改里面<label>的</label>文本<label><input type="file" /></label>

[英]How to change text inside <label> with the file name of <input type="file" />

我正在尝试使用<input type="file" />所选文件的名称更改<label>标签内的文本

我试过这个,但它不起作用:

<!DOCTYPE html>
<html>    
  <head>
    <script type="text/javascript" src="jquery-1.12.4.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
      $('#files').on("change",function() {
        console.log("change fired");
        var i = $(this).prev('label').clone();
        var file = $('#files')[0].files[0].name;
        console.log(file);
        $(this).prev('label').text(file);        
      });
    </script>
  </head>
  <body>
    <div class="upload_firmware_container">
      Please upload the provided <span style="color:#e11422">firmware.bin</span> file and/or <span style="color:#e11422">spiffs.bin</span> file.</br>              
      <!-- action="/doUpdate" -->
      <form method="POST" enctype="multipart/form-data">
        <label class="file_input_label" for="files">Browse files</label>
        <input id="files" type="file" name="update">
        <input class="upload_button" type="submit" name="getUpdate" value="Update">
      </form>
    </div>
  </body>
</html>

如您所见,我有 2 个脚本源。 第一个是本地的,它适用于我所有的小脚本。 我添加了第二个,因为我在我受到启发的示例中找到了它。

你怎么认为? 欢迎使用 jQuery。

解决:

它不起作用,因为脚本必须在相关元素之后。 HTML页面的末尾移动脚本解决了所有问题。

原因是因为 html 从上到下加载,并且您的代码在页面上加载任何元素之前运行脚本。

一种解决方案:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="jquery-1.12.4.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="upload_firmware_container">
  Please upload the provided <span style="color:#e11422">firmware.bin</span> file and/or <span style="color:#e11422">spiffs.bin</span> file.</br>
  <!-- action="/doUpdate" -->
  <form method="POST" enctype="multipart/form-data">
    <label class="file_input_label" for="files">Browse files</label>
    <input id="files" type="file" name="update">
    <input class="upload_button" type="submit" name="getUpdate" value="Update">
  </form>
</div>
</body>
<script>
  $('#files').on("change",function() {
    console.log("change fired");
    var i = $(this).prev('label').clone();
    var file = $('#files')[0].files[0].name;
    console.log(file);
    $(this).prev('label').text(file);
  });
</script>
</html>

更多解决方案参考这篇文章: stackoverflow.com

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM