Javascript 如何在 jQuery 中处理 input type=file 上的 onchange 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11860721/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:26:02  来源:igfitidea点击:

How to handle onchange event on input type=file in jQuery?

javascriptjqueryhtmleventsinput

提问by anmarti

The code is:

代码是:

<input ID="fileUpload1" runat="server" type="file"

The following works fine:

以下工作正常:

<input onchange="javascript:alert('hola');" ID="fileUpload1"  runat="server" type="file"

I'd like to get this result using jQuery, but that doesn't work:

我想使用 jQuery 得到这个结果,但这不起作用:

$('#fileUpload1').change(function (e) {
    alert("hola");
});

I am missing something? (Edit: Yes I missed include the *.js file.)

我错过了什么?(编辑:是的,我错过了包含 *.js 文件。)

回答by Shabnam K

Demo : http://jsfiddle.net/NbGBj/

演示:http: //jsfiddle.net/NbGBj/

$("document").ready(function(){

    $("#upload").change(function() {
        alert('changed!');
    });
});

回答by Alex Ball

Or could be:

或者可以是:

$('input[type=file]').change(function () {
    alert("hola");
});

To be specific: $('input[type=file]#fileUpload1').change(...

再具体一点: $('input[type=file]#fileUpload1').change(...

回答by Chris

It should work fine, are you wrapping the code in a $(document).ready()call? If not use that or use livei.e.

它应该可以正常工作,您是否将代码包装在$(document).ready()调用中?如果不使用那个或使用liveie

$('#fileupload1').live('change', function(){ 
    alert("hola");
});

Here is a jsFiddleof this working against jQuery 1.4.4

这是一个针对 jQuery 1.4.4的jsFiddle

回答by Simon

This jsfiddleworks fine for me.

这个jsfiddle对我来说很好用。

$(document).delegate(':file', 'change', function() {
    console.log(this);
});

Note: .delegate() is the fastest event-binding method for jQuery < 1.7: event-binding methods

注意:.delegate() 是 jQuery < 1.7: event-binding methods 中最快的事件绑定方法

回答by Arpit Srivastava

Try to use this:

尝试使用这个:

HTML:

HTML:

<input ID="fileUpload1" runat="server" type="file">

JavaScript:

JavaScript:

$("#fileUpload1").on('change',function() {
    alert('Works!!');
});

?

?

回答by Bhushan Pawar

 $('#fileupload').bind('change', function (e) { //dynamic property binding
alert('hello');// message you want to display
});

You can use this one also

你也可以用这个