Как создать таблицу с неактивными ячейками - PullRequest
1 голос
/ 19 июня 2020

Мне нужно создать таблицу для выбора фильтров массива с условиями здесь, например, начало таблицы для фильтров (вы не можете выбрать клиента и пользователя одновременно):

enter image description here

для этого я создаю таблицу с идентификатором по ячейке:

jQuery(document).ready(function($) {

    filter = {
        date: 0,
        client: 0,
        user: 0
    };

    $(".blank_row > td").click(function() {
       if (filter['date'] == 0 && $(this).attr('id') == 'date') {
            filter[$(this).attr('id')] = 1;
            $(this).addClass("bg-success");
        }
        else if (filter['date'] == 1 && $(this).attr('id') == 'date') {
            $(this).removeClass("bg-success");
            filter[$(this).attr('id')] = 0;
        }
    
        if (filter['client'] == 0 && filter['user'] == 0 && $(this).attr('id') != 'date') {
            filter[$(this).attr('id')] = 1;
            $(this).addClass("bg-success");
        } else if (filter['client'] == 1 || filter['user'] == 1) {
            $(this).removeClass("bg-success");
            filter[$(this).attr('id')] = 0;
        }
    
        console.log($(this).attr('id'));
        console.log(filter);
    });

});
.blank_row {
    height: 50px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<table id="graphTable" class="table table-sm table-bordered">
            <thead>
                <tr>
                    <th class="border" colspan="3">FILTER</th>
                </tr>
                <tr>
                    <th>DATE</th>
                    <th>CLIENT</th>
                    <th>USER</th>
                </tr>
            </thead>
            <tbody>
                <tr class="blank_row">
                    <td id="date"></td>
                    <td id="client"></td>
                    <td id="user"></td>
                </tr>
            </tbody>
        </table>

но если я хочу добавить новые ячейки, я быстро потеряюсь с кодом, который я уже сделал. У вас есть какое-нибудь другое решение, чтобы сделать то, что я хочу, проще?

1 Ответ

1 голос
/ 20 июня 2020

Вы можете использовать hasClass метод jquery, чтобы узнать, имеет ли tds требуемый класс или нет, в зависимости от этого мы можем addClass или removeClass из любого конкретного tds.

Демо-код :

$(document).ready(function($) {

  $(".blank_row > td").click(function() {
  //get td closest tr(index)
    var rowIndex = $(this).closest("tr").index();
    //getting cell no of td which is clicked
    var cell = $(this).index();
    //looping over the tr
    $('tbody > tr:eq(' + rowIndex + ') ').each(function(cellIndex){
    
      var selectors = $(this).find("td:eq(" + cell + ")");
  //checking if the clicked td has some classes or not
   if (!(selectors.hasClass("bg-success")) && (selectors.hasClass("date"))) {
        //add
        selectors.addClass("bg-success");
      } else if (selectors.hasClass("date") && selectors.hasClass("bg-success")) {
        //removed
        selectors.removeClass("bg-success");
      }
 //checking if the client and user has bg-success or not
      if (!($(this).find(".client").hasClass('bg-success')) && !($(this).find(".user").hasClass('bg-success')) && !(selectors.hasClass("date"))) {
        //add
        selectors.addClass("bg-success");
      } else if ((($(this).find(".client").hasClass('bg-success')) || ($(this).find(".user").hasClass('bg-success'))) && !(selectors.hasClass("date"))) {
        //removed
        selectors.removeClass("bg-success");
      }

   });
 });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<table id="graphTable" class="table table-sm table-bordered">
  <thead>
    <tr>
      <th class="border" colspan="3">FILTER</th>
    </tr>
    <tr>
      <th>DATE</th>
      <th>CLIENT</th>
      <th>USER</th>
    </tr>
  </thead>
  <tbody>
    <tr class="blank_row">
      <td class="date">a</td>
      <td class="client">b</td>
      <td class="user">c</td>
    </tr>
    <tr class="blank_row">
      <td class="date">a1</td>
      <td class="client">b1</td>
      <td class="user">c1</td>
    </tr>
    <tr class="blank_row">
      <td class="date">a2</td>
      <td class="client">b2</td>
      <td class="user">c2</td>
    </tr>
  </tbody>
</table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...