我正在使用input type=file的replaceWith来处理用户想要上传的文件的更改。
我有这样的代码:
$('#add_cv_input').change(function() {
// here is some code
else {
alert('put one of this: pdf doc docx');
$("#add_cv_input").replaceWith('<input id="add_cv_input" type="file"/>');
}
});现在的问题是,在用户第一次上传错误的扩展之后,这个jquery changed事件不会被调用。
我不知道为什么会发生这样的事情。如果用户第一次上传一个有效的扩展名,然后将其更改为其他有效的扩展名,则一切正常。
发布于 2012-10-14 05:35:34
当您销毁第一项时,事件处理程序也会随之销毁。如果希望事件处理程序位于新项上,则有两种选择:
将委托事件处理与.on()的动态形式一起使用可能是最简单的
$(some parent selector).on('change', '#add_cv_input', function() {
// code here
});其中,您选择了一些尽可能接近#add_cv_input的父选择器,但不会被销毁。
如果你想在替换元素后重新附加事件处理程序,你可以这样做(尽管委托事件处理会更干净):
function processChange() {
// here is some code
else {
alert('put one of this: pdf doc docx');
$("#add_cv_input").replaceWith('<input id="add_cv_input" type="file"/>');
$('#add_cv_input').change(processChange);
}
});
$('#add_cv_input').change(processChange);发布于 2012-10-14 05:35:54
您正在销毁事件处理程序绑定到的原始元素,这就是它不会再次触发的原因。尝试重置元素,而不是替换元素。
编辑:考虑到重置单个文件输入很重要(因为this.value = null;不能在所有浏览器上工作),替换元素似乎是更好的选择。
您可以只将事件处理程序附加到新创建的元素。[.replaceAll()]
function cv_input_file(){
// here is some code
else {
alert('put one of this: pdf doc docx');
$('<input id="add_cv_input" type="file"/>')
.replaceAll("#add_cv_input")
.change(cv_input_file);
}
}
$('#add_cv_input').change(cv_input_file);或者使用事件委托,这样就不必在每次替换元素时都添加处理程序。
$(document/*or the closest static ancestor*/).on('change', '#add_cv_input', function() {
// here is some code
else {
alert('put one of this: pdf doc docx');
$("#add_cv_input").replaceWith('<input id="add_cv_input" type="file"/>');
}
});https://stackoverflow.com/questions/12877196
复制相似问题