简体   繁体   中英

When appending a font awesome icon in a button using jQuery the icon disappears when I click another button

I am making a to do list web app using jQuery. I have a grey bootstrap button with an empty box icon (from font awesome) to show an item is incomplete. When the user completes the task I want the button to become green and the icon to change into a checked box icon (from font awesome also). I can get the button to become green by changing the class and the icon to change for one item however when I click another item to mark as complete the previous button stays green however the checked box icon disappears.

Essentially the code for the icon which is <i class="fa fa-check-square-o"></i> gets removed from the code of the first button that is clicked once the second button is clicked however the previous button still stays green. The same thing happens to the second button when I click a third button. How can I get <i class="fa fa-check-square-o"></i> to stay? Thanks in advance for any help.

var checked = $("<i>").addClass("fa fa-check-square-o");

  $("table").on("click", ".btn-default", function(){
    $(this).replaceWith($("<button>").attr("type", "button").addClass("btn btn-success").append(checked));
  });

simply put the checked element into click scope

  $(document).on("click", ".btn-default", function(){
      checked = $("<i>").addClass("fa fa-check-square-o");
      $(this).replaceWith($("<button>").attr("type", "button").addClass("btn btn-success").append(checked));
  });

otherwise it will always reference the same <i> element and append it to the next clicked button

尝试简化这条线

$(this).replaceWith("<button type='button' class='btn btn-success'><li class='fa fa-check-square-o'></li></button");

Move the declaration of var checked into the click handler. The reason is that you're creating a single element and moving it around each time you call .append.

From the .append docs

http://api.jquery.com/append/

"If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned)"

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