简体   繁体   English

类更改后元素丢失属性

[英]Element loses properties after class change

I was wondering, why changing an element's class (haven't tried with id), makes it not responsive to functions that work with the class set? 我想知道,为什么更改元素的类(未尝试使用id进行尝试),使其无法响应与该类集一起使用的功能?

Example

js function 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);
        });
    });
}

DOM DOM

<div class="has-img">
   <a class="remove-image"> Remove Image </a>
   <img src="blalbalba.jpg" />
</div>

js code js代码

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

addImg('.has-img img, .no-img');

After .removeClass('has-img').addClass('no-img') the addImg('.has-img img, .no-img'); .removeClass('has-img').addClass('no-img') addImg('.has-img img, .no-img'); function doesn't work anymore for that element. 该功能不再适用于该元素。 Why is that? 这是为什么?

The binding only works on elements that have one of those classes at the time the event is bound. 绑定仅适用于绑定事件时具有这些类之一的元素。 Try this: 尝试这个:

$(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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM