jQuery - 检测文件输入中是否选择了文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5670769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Detecting if a file has been selected in the file input
提问by BigJobbies
Possible Duplicate:
jQuery: get the file name selected from <input type=“file” />
I have a standard file input box
我有一个标准的文件输入框
<input type="file" name="imafile">
I also have a bit of text down the page like so
我也有一些像这样的文字
<span class="filename">Nothing selected</span>
I was wondering if it is possible to have the text update with the name of the file selected in the file input box?
我想知道是否可以使用在文件输入框中选择的文件名更新文本?
Cheers,
干杯,
回答by Clayton
You should be able to attach an event handler to the onchange event of the input and have that call a function to set the text in your span.
您应该能够将事件处理程序附加到输入的 onchange 事件,并调用一个函数来设置跨度中的文本。
<script type="text/javascript">
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$(".filename").html(fileName);
});
});
</script>
You may want to add IDs to your input and span so you can select based on those to be specific to the elements you are concerned with and not other file inputs or spans in the DOM.
您可能希望将 ID 添加到您的输入和跨度,以便您可以根据特定于您关注的元素而不是 DOM 中的其他文件输入或跨度的 ID 进行选择。
回答by James Khoury
I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has
我建议尝试更改事件?测试它是否有值,如果有,那么你可以继续你的代码。jQuery 有
.bind("change", function(){ ... });
Or
或者
.change(function(){ ... });
which are equivalents.
它们是等价的。
for a unique selector change your name attribute to id and then jQuery("#imafile")
or a general jQuery('input[type="file"]')
for all the file inputs
对于唯一的选择器,将您的 name 属性更改为 id 然后jQuery("#imafile")
或jQuery('input[type="file"]')
所有文件输入的通用