Как скрыть, показать и повторно скрыть и повторно показать tr в таблице в HTML - PullRequest
0 голосов
/ 03 июля 2018

Предположительно, у меня есть опция выбора. Таблица должна отображать только строку в таблице, основываясь на моей опции в теге select.

Допустим, я выбрал первый вариант, и его значение равно A, остальные строки, которые не содержат только «A», будут скрыты. Но когда дело доходит до опции BB, предположительно в таблице отображается только строка, содержащая только текст «BB», третья строка успешно скрыта, но затем первая строка все еще там.

$(document).ready(function() {
  $("button").click(function() {
    var searchString = $('#enter').find(":selected").text();
    $("#mytable tr td:contains('" + searchString + "')").each(function() {
      if ($(this).text() != searchString) {
        $(this).parent().hide();
      } else {
        $(this).parent().show();
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="enter">
  <option value="A">A</option>
  <option value="BB">BB</option>
  <option value="CCC">CCC</option>
</select>

<button>Set text content for all p elements</button>

<table border="0" align="center" width="45%" cellpadding="2" cellspacing="2" id="mytable">
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
  </tr>
  <tr>
    <td>AA</td>
    <td>BB</td>
    <td>CC</td>
  </tr>
  <tr>
    <td>AAA</td>
    <td>BBB</td>
    <td>CCC</td>
  </tr>
</table>

Мой jQuery корректен или имеет логическую ошибку?

Ответы [ 4 ]

0 голосов
/ 04 июля 2018
your selector "#mytable tr td:contains('" + searchString + "')" starts the loop right 
after it find the element. which was causing the issue . try below

 ` $(document).ready(function() {
      $("button").click(function() {
        var searchString = $('#enter').find(":selected").text();
        var trs = $('#mytable').find('tr');
        trs.each(function(i, ele) {
          $(ele).children('td').each(function(j, ele1) {
            if ($(ele1).text() != searchString) {
              $(ele1).parent().hide();
            } else {
              $(ele1).parent().show();
              return false;
            }
          })
        })
      });
    });`
0 голосов
/ 03 июля 2018

Вы должны изменить мелочь в своем коде .. Сделайте свою логику такой:

1) Сначала Скрыть все <tr>

2) Затем найдите строку в <tr> и покажите их ..

Пример в вашем коде:

    $(document).ready(function() {
      $("button").click(function() {
      var searchString = $('#enter').find(":selected").text();
      $('tr').hide(); //<------First Update
      $("#mytable tr td:contains('" + searchString + "')").each(function() {
       $(this).parent().show();  //<------Second update
       });
     });
   });

Я также делаю полное кодирование. Вы можете проверить это ..

Ссылка JSFiddle: https://jsfiddle.net/cebL4jpv/5/

0 голосов
/ 03 июля 2018

Ваш код не учитывает, когда строка была скрыта, но тогда один из братьев и сестер таблицы не содержит строку. Например, каждая функция достигает CC, которая не содержит BB, а затем снова отображается родительский элемент.

Я исправил ваш код, надеюсь, это поможет.

$(document).ready(function() {
  $("button").click(function() {
    var searchString = $('#enter').find(":selected").text();
    $("#mytable tr td").each(function() {
      if ($(this).text().indexOf() > -1 || $(this).siblings().text().indexOf(searchString) > -1 ) {
        $(this).parent().hide();
      } else {
        $(this).parent().show();
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="enter">
  <option value="A">A</option>
  <option value="BB">BB</option>
  <option value="CCC">CCC</option>
</select>

<button>Set text content for all p elements</button>

<table border="0" align="center" width="45%" cellpadding="2" cellspacing="2" id="mytable">
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
  </tr>
  <tr>
    <td>AA</td>
    <td>BB</td>
    <td>CC</td>
  </tr>
  <tr>
    <td>AAA</td>
    <td>BBB</td>
    <td>CCC</td>
  </tr>
</table>
0 голосов
/ 03 июля 2018

Чтобы это работало, вам необходимо выполнить точное совпадение с содержимым элементов td. :contains по умолчанию является жадным совпадением, поэтому поиск A будет соответствовать всем трем строкам. Чтобы это исправить, вы можете использовать filter():

$("button").click(function() {
  var searchString = $('#enter').val();

  $("#mytable tr").hide().find('td').filter(function() {
    return $(this).text().trim() === searchString;
  }).parent().show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="enter">
  <option value="A">A</option>
  <option value="BB">BB</option>
  <option value="CCC">CCC</option>
</select>

<button>Set text content for all p elements</button>

<table border="0" align="center" width="45%" cellpadding="2" cellspacing="2" id="mytable">
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
  </tr>
  <tr>
    <td>AA</td>
    <td>BB</td>
    <td>CC</td>
  </tr>
  <tr>
    <td>AAA</td>
    <td>BBB</td>
    <td>CCC</td>
  </tr>
</table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...