输入类型=“文件"的jQuery更改方法 [英] jQuery change method on input type="file"

查看:35
本文介绍了输入类型=“文件"的jQuery更改方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 100% 使用 jQuery,它的 API 简单而优雅,但我遇到了 API 和直接 HTML 之间的不一致,我不太明白.

I'm trying to embrace jQuery 100% with it's simple and elegant API but I've run into an inconsistency between the API and straight-up HTML that I can't quite figure out.

我有一个 AJAX 文件上传器脚本(可以正常运行),每次文件输入值更改时我都想运行它.这是我的工作代码:

I have an AJAX file uploader script (which functions correctly) that I want to run each time the file input value changes. Here's my working code:

<input type="file" size="45" name="imageFile" id="imageFile" onchange="uploadFile()">

当我将 onchange 事件转换为 jQuery 实现时:

When I convert the onchange event to a jQuery implementation:

$('#imageFile').change(function(){ uploadFile(); });

结果不一样.使用 onchange 属性,只要值按预期更改,就会调用 uploadFile() 函数.但是使用 jQuery API .change() 事件处理程序,该事件仅在值第一次更改时触发.之后的任何值更改都将被忽略.这对我来说似乎是错误的,但这肯定不是 jQuery 的疏忽,对吧?

the result isn't the same. With the onchange attribute the uploadFile() function is called anytime the value is changed as is expected. But with the jQuery API .change() event handler, the event only fires the first time a value is change. Any value change after that is ignored. This seems wrong to me but surely this can't be an oversight by jQuery, right?

有没有其他人遇到过同样的问题,除了我上面描述的问题之外,您有解决方法或解决方案吗?

Has anyone else encountered the same issue and do you have a workaround or solution to the problem other than what I've described above?

推荐答案

ajax 上传器是否刷新了你的输入元素?如果是这样,您应该考虑使用 .live() 方法.

is the ajax uploader refreshing your input element? if so you should consider using .live() method.

 $('#imageFile').live('change', function(){ uploadFile(); });

更新:

从 jQuery 1.7+ 你现在应该使用 .on()

from jQuery 1.7+ you should use now .on()

 $(parent_element_selector_here or document ).on('change','#imageFile' , function(){ uploadFile(); });

这篇关于输入类型=“文件"的jQuery更改方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆