JQuery on_click: removeClass in a button then toggleClass another (only one button has the class)

JQuery on_click: removeClass in a button then toggleClass another (only one button has the class)

我的每个循环按钮:

<td class="p-0 btn-category-list-col">
   <button type="button" value="${cat.category_id}" data-id="${cat.category_id}" class="category_sort btn float-left" data-toggle="modal" data-target="#createCategory">${cat.category_name}</button>
</td>

点击代码。只显示问题的相关行

        $(document).on('click', '.category_sort', function (e) {
        e.preventDefault();
            let id = event.target.dataset.id;
                if (id) {
                    $(`button[data-id=${id}]`).toggleClass("btn-category-list-col-click");
                }
        });

当 运行 上面的代码时,class 会切换,但是当我单击另一个按钮时,由于 [=16=,前一个按钮仍然具有预期的 class ]

我希望把上一个按钮的btn-category-list-col-click去掉,让新点击的按钮得到它。

我尝试先堆叠 removeClass 然后 toggleClass 但 class 仍然存在:

            let id = event.target.dataset.id;
                if (id) {
                    $(`button[data-id=${id}]`).removeClass("btn-category-list-col-click");
                    $(`button[data-id=${id}]`).toggleClass("btn-category-list-col-click");
                }

使用 each,滚动浏览所有具有 .category_sort class 的元素并从中删除 btn-category-list-col-click class,然后将其添加到btn-category-list-col-click class.

的当前对象
$(document).on('click', '.category_sort', function (e) {
    e.preventDefault();
    $(".category_sort").each(function() {
       $(this).removeClass("btn-category-list-col-click");
    });
    $(this).addClass("btn-category-list-col-click");
});

//btn-category-list-col-click

$(document).on('click', '.category_sort', function (e) {
    e.preventDefault();
    $(".category_sort").removeClass("btn-category-list-col-click");   
    $(this).addClass("btn-category-list-col-click");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="p-0 btn-category-list-col">
      <button type="button" class="category_sort">cat.category_name1</button>
    </td>
  </tr>
  <tr>
    <td class="p-0 btn-category-list-col">
      <button type="button" class="category_sort">cat.category_name2</button>
    </td>
  </tr>
  <tr>
    <td class="p-0 btn-category-list-col">
      <button type="button" class="category_sort">cat.category_name3</button>
    </td>
  </tr>
  <tr>
    <td class="p-0 btn-category-list-col">
      <button type="button" class="category_sort">cat.category_name4</button>
    </td>
  </tr>
</table>