2012-08-08 97 views
40

的代码是:如何在jQuery中处理input type = file的onchange事件?

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

下正常工作:

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

我想获得使用jQuery这样的结果,但是,这并不工作:

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

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

+1

元素的ID是' “fileUpload1”''没有 “fileupload1”'。你是否也在元素存在之后运行你的代码,并且你包含了jQuery等?同时检查您的浏览器控制台是否有javascript错误 – Esailija 2012-08-08 08:40:13

+0

我搜索了类似的关键字,但我在寻找“没有jQuery”版本... – 2016-10-14 05:30:55

回答

2

尝试使用此:

HTML:

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

的JavaScript:

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

+2

错误的事件和错误的ID。 – Esailija 2012-08-08 08:41:32

+0

对不起,我没有正确地看到问题...现在检查@Esailija – 2012-08-08 08:54:29

4

它应该w奥克罚款,你打电话给$(document).ready()电话的代码?如果不使用或使用live

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

下面是这个工作的jsFiddle反对的jQuery 1.4.4

+3

住不用了,现在应该使用()现在 – Simon 2012-08-08 08:42:10

+1

他使用的v1.4.4不支持'on()' – Chris 2012-08-08 08:47:34

+3

'live'是已弃用所有jQuery版本,请使用'.delegate' – Esailija 2012-08-08 08:49:33

3

jsfiddle工作正常,我。

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

注:.delegate()是jQuery的< 1.7最快的事件结合方法:event-binding methods

+0

1.4.4。 Dosent'工作。 – anmarti 2012-08-08 08:46:18

+0

更新了我的答案 – Simon 2012-08-08 08:55:45

8

或者可能是:

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

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

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

您可以使用这其中也

相关问题