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

3

我试图通过从 <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>

如您所见,我有两个脚本来源。第一个是本地的,它可以与我所有的小脚本一起使用。我添加了第二个,因为我在灵感来源的示例中发现了它。

您认为呢? 欢迎使用jQuery。

解决方法:

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


1
它不能工作是因为脚本在元素出现之前运行...你不能在元素存在之前找到它。 - epascarello
2
将脚本代码移到最后。 - Karan
1
无论何时你要针对一个DOM元素进行操作,请确保该DOM在被操作时已经可用,或者使用window.onload事件,并将你的代码写在该事件中。 - Krishna Prashatt
你说得非常正确!它起作用了!太棒了!谢谢大家! - bleah1
作为一个经验法则,即使我的其他脚本是否针对DOM元素,我也可以将它们全部移动到页面末尾吗?它们还能正常工作吗? - bleah1
脚本应在DOM加载后运行(大多数情况下)。但是,最好不要将它们粘贴到HTML文件的末尾,而是将它们外部化为自己的.js文件,然后在关闭</body>标记之前调用该文件。还要记住,如果您有多个.js文件,在HTML文件中调用它们时顺序很重要。 - Sergio
1个回答

1
由于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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接