简体   繁体   中英

remove element with specific class only when other class is active

I have an element that can be removed when it has the class "edit-mode". The class "edit-mode" is toggled by a button. The problem here is that when the "edit-mode" class gets removed, this element can be removed on click which shouldn't happen.

Consider the following code :

 $(document).ready(function() { $('.active-edit-mode').click(function() { $('.my-element').toggleClass('edit-mode'); $('.active-edit-mode').toggleClass('edit-mode'); $('.my-element.edit-mode').click(function() { $(this).remove(); }); }); }); 
 .my-element { color: #007aff; cursor: pointer; } .edit-mode { font-weight: bold; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="elements"> <div class="my-element"> this element </div> <div class="my-element"> this element </div> <div class="my-element"> this element </div> </div> <button class="active-edit-mode"> active edit mode </button> 

Jsfiddle : jsfiddle

You should check this logic in the onClick event handler of .my-element , this would be more clearer.

 $(document).ready(function(){ $('.active-edit-mode').click(function(){ $('.my-element').toggleClass('edit-mode'); $('.active-edit-mode').toggleClass('edit-mode'); }); $('.my-element').click(function(){ if ($(this).hasClass('edit-mode')) { console.log('click removing') $(this).remove(); } }); }); 
 .my-element { color: #007aff;cursor:pointer; } .edit-mode {font-weight:bold;} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="elements"> <div class="my-element"> this element </div> <div class="my-element"> this element </div> <div class="my-element"> this element </div> </div> <button class="active-edit-mode"> active edit mode </button> 

It will work if you bind the removal function independently. Your JS would look like:

$(document).ready(function(){
    $('.active-edit-mode').click(function(){
    $('.my-element').toggleClass('edit-mode');
    $('.active-edit-mode').toggleClass('edit-mode');
  });
});
$(document).on('click','.my-element.edit-mode',function(){
    $(this).remove();
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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