首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jquery replaceWith含义

jquery replaceWith含义
EN

Stack Overflow用户
提问于 2012-10-14 05:31:56
回答 2查看 279关注 0票数 0

我正在使用input type=file的replaceWith来处理用户想要上传的文件的更改。

我有这样的代码:

代码语言:javascript
复制
$('#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事件不会被调用。

我不知道为什么会发生这样的事情。如果用户第一次上传一个有效的扩展名,然后将其更改为其他有效的扩展名,则一切正常。

EN

回答 2

Stack Overflow用户

发布于 2012-10-14 05:35:34

当您销毁第一项时,事件处理程序也会随之销毁。如果希望事件处理程序位于新项上,则有两种选择:

  1. 创建新对象后,您可以在新对象上重新安装事件处理程序。
  2. 您可以使用未销毁的父级的委托事件处理。

将委托事件处理与.on()的动态形式一起使用可能是最简单的

代码语言:javascript
复制
$(some parent selector).on('change', '#add_cv_input', function() {
    // code here
});

其中,您选择了一些尽可能接近#add_cv_input的父选择器,但不会被销毁。

如果你想在替换元素后重新附加事件处理程序,你可以这样做(尽管委托事件处理会更干净):

代码语言:javascript
复制
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);
票数 4
EN

Stack Overflow用户

发布于 2012-10-14 05:35:54

您正在销毁事件处理程序绑定到的原始元素,这就是它不会再次触发的原因。尝试重置元素,而不是替换元素。

编辑:考虑到重置单个文件输入很重要(因为this.value = null;不能在所有浏览器上工作),替换元素似乎是更好的选择。

您可以只将事件处理程序附加到新创建的元素。[.replaceAll()]

代码语言:javascript
复制
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);

或者使用事件委托,这样就不必在每次替换元素时都添加处理程序。

代码语言:javascript
复制
$(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"/>');
    }
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12877196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档