简体   繁体   中英

How do I change icon with Jquery?

I have any AJAX call that allow to select an item, I'm displaying the selected item with a darker background and the icon marked selected.

I can change the background but when I attempt to change the icon doesn't work. Somebody can explain what I'm doing wrong?

Here it is the code

$("#accounts-list").on('click', '.nav-link', function () {
  var object_id = $(this).data('object-id');
  $.ajax({
    url: "url_to_ajax_call.php",
    data: {
      'account_id': object_id
    },
    type: 'POST',
    success: function (response) {
      // remove class where previously selected
      $(".nav-link").removeClass("bg-soft-primary"); // background
      $(".nav-link>span.fa-check-circle").removeClass("fa-check-circle").addClass("fa-circle"); // remove checked icon

      // apply selected class to the new item
      let item = $('.nav-link[data-object-id=' + object_id + ']');
      item.addClass('bg-soft-primary'); // apply background
      $(item + ">span.fa-circle").removeClass("fa-circle").addClass("fa-circle"); // select checked icon
    }
  })
})

    <div id="accounts-list">
      <ul class="nav">
        <li class="nav-item">
          <div class="nav-link nav-link-card-details bg-soft-primary"
               data-object-id="1">
            <span class="far fa-check-circle"></span>
            Item 1
          </div>
        </li>
        <li class="nav-item">
          <div class="nav-link nav-link-card-details"
               data-object-id="2">
            <span class="far fa-circle"></span>
            Item 2
          </div>
        </li>
        <li class="nav-item">
          <div class="nav-link nav-link-card-details"
               data-object-id="3">
            <span class="far fa-circle"></span>
            Item 3
          </div>
        </li><li class="nav-item">
        <div class="nav-link nav-link-card-details"
             data-object-id="4">

          <span class="far fa-circle"></span>
          Item 4
        </div>
        </li>
        </li>
      </ul>
    </div>

Thank you

In $(item + ">span.fa-circle") , item is not a string to be used has a selector... It is a jQuery object.

So do it like this:

item.find("span.far")

Ho, To notice any effect; the should be two fontAwesome classes (one added and one different removed ;)

.removeClass("fa-check-circle").addClass("fa-circle")

Another way would be:

.toggleClass("fa-check-circle fa-circle")

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