Javascript 元素在类更改后丢失属性

Javascript 元素在类更改后丢失属性,javascript,jquery,function,Javascript,Jquery,Function,我想知道,为什么更改元素的类(没有尝试使用id)会使它对使用类集的函数没有响应 范例 js函数 function addImg(element) { $(element).click(function() { var $block = $(this).is('img') ? $(this).parent() : $(this); var $name = $block.attr('id'); $('input[name="'+$name+'

我想知道,为什么更改元素的类(没有尝试使用id)会使它对使用类集的函数没有响应

范例

js函数

function addImg(element) {
    $(element).click(function() {
        var $block = $(this).is('img') ? $(this).parent() : $(this);
        var $name  = $block.attr('id');
        $('input[name="'+$name+'"]').click();
        $('input[name="'+$name+'"]').change(function() {
            $block.css('border-color', '#cecece')
            readURL(this, $block);
        });
    });
}
多姆


之后.removeClass('has-img').addClass('no-img')
addImg('has-img,'no-img')函数不再适用于该元素。为什么会这样?

绑定只在绑定事件时具有其中一个类的元素上起作用。试试这个:

$(document).on('click', '.has-img img, .no-img', function() {
    var $block = $(this).is('img') ? $(this).parent() : $(this);
    var $name  = $block.attr('id');
    $('input[name="'+$name+'"]').click();
    $('input[name="'+$name+'"]').change(function() {
        $block.css('border-color', '#cecece')
        readURL(this, $block);
    });
});

$(document).on('click', '.remove-image', function() {
    $(this).parent().removeClass('has-img').addClass('no-img').find('img').remove();
    $(this).remove();
});

绑定仅适用于在绑定事件时具有这些类之一的元素。试试这个:

$(document).on('click', '.has-img img, .no-img', function() {
    var $block = $(this).is('img') ? $(this).parent() : $(this);
    var $name  = $block.attr('id');
    $('input[name="'+$name+'"]').click();
    $('input[name="'+$name+'"]').change(function() {
        $block.css('border-color', '#cecece')
        readURL(this, $block);
    });
});

$(document).on('click', '.remove-image', function() {
    $(this).parent().removeClass('has-img').addClass('no-img').find('img').remove();
    $(this).remove();
});

哇哦。。。伟大的提示,使用
$(文档)
woho。。。使用
$(文档)
$(document).on('click', '.has-img img, .no-img', function() {
    var $block = $(this).is('img') ? $(this).parent() : $(this);
    var $name  = $block.attr('id');
    $('input[name="'+$name+'"]').click();
    $('input[name="'+$name+'"]').change(function() {
        $block.css('border-color', '#cecece')
        readURL(this, $block);
    });
});

$(document).on('click', '.remove-image', function() {
    $(this).parent().removeClass('has-img').addClass('no-img').find('img').remove();
    $(this).remove();
});