我正在尝试更改 <label>
中的文本带有从 <input type="file" />
中选择的文件名的标签
我试过了,但是不行:
<!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
关于javascript - 如何使用 <input type ="file"/> 的文件名更改 <label> 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56952724/