Как я могу toggle() показать/скрыть следующую строку таблицы при нажатии на любую из строк

Как я могу toggle() скрыть/показать содержимое следующей строки таблицы, когда я нажимаю на любые строки? Я пытаюсь создать расширяемую строку таблицы.

Это мой код Javascript: здесь я пытаюсь изначально скрыть, что все строки не имеют class="accordion" затем при любом щелчке по любой строке мне нужно показать следующий элемент строки (rowContent)

 $(function() {
            var $research = $('.treat-table');
            $research.find("tr").not('.accordion').hide();
            $research.find("tr").eq(0).show();

            $research.find(".accordion").click(function(){
                $(this).next("tr").toggle();
            })
        });
table.basic-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  border: none;
  margin-bottom: 15px;
}

table.basic-table th {
  background-color: #66676b;
  text-align: left;
  color: #fff;
  vertical-align: top;
  font-weight: 500;
}

table.basic-table th:first-child {
  border-radius: 4px 0 0 4px;
}

table.basic-table th:last-child {
  border-radius: 0 4px 4px 0;
}

table.basic-table th,
table.basic-table td {
  padding: 15px 28px;
}

table.basic-table tr:nth-child(odd) {
  background-color: #f6f6f6
}

table.basic-table {
  margin-bottom: 0;
}
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity = "sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin = "anonymous">
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity = "sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin = "anonymous"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity = "sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin = "anonymous"></script>


<table class = "basic-table treat-table">

  <tr>
    <th>ID</th>
    <th>Category</th>
    <th>Treatment Name</th>
    <th>Price</th>
    <th>+</th>
  </tr>
 
  <!-- Row -->
  <tr class = "accordion">
    <td>1</td>
    <td>Plastic surgery</td>
    <td>Nose job</td>
    <td>from 2000$</td>
    <td>+</td>
  </tr>
  <tr class = "rowContent">
    <td colspan = "5">
    <h5>This is content</h5>
    <p>This area show hided content</p>
    </td>
  </tr>
 <!-- Row -->
  <tr class = "accordion">
    <td>1</td>
    <td>Plastic surgery</td>
    <td>Nose job</td>
    <td>from 2000$</td>
    <td>+</td>
  </tr>
  <tr class = "rowContent">
    <td colspan = "5">
    <h5>This is content</h5>
    <p>This area show hided content</p>
    </td>
  </tr>


</table>

Я пытаюсь использовать метод next(), чтобы выбрать следующий элемент, а затем вызвать метод toggle() в моей функции, работающей по щелчку любой строки.

Похоже, вы нигде не используете свой класс .research.

Barrosy 21.01.2019 11:50

Я редактирую его и добавляю класс таблицы лечения в свой <table>

Reza 21.01.2019 12:05

Выглядит хорошо для меня, он работает, как ожидалось. Не так ли?

bhansa 21.01.2019 12:13
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
3
1 011
2

Ответы 2

Похоже, что 2 вещи происходят. С одной стороны, класс .research не используется, а с другой стороны, Toggle() не существует. Проверьте переключатель(). Надеюсь, поможет.

$(function() {
            var $research = $('.research');
            $research.find("tr").not('.accordion').hide();
            $research.find("tr").eq(0).show();

            $research.find(".accordion").click(function(){
                $(this).next("tr").toggle();
            })
        });
table.basic-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  border: none;
  margin-bottom: 15px;
}

table.basic-table th {
  background-color: #66676b;
  text-align: left;
  color: #fff;
  vertical-align: top;
  font-weight: 500;
}

table.basic-table th:first-child {
  border-radius: 4px 0 0 4px;
}

table.basic-table th:last-child {
  border-radius: 0 4px 4px 0;
}

table.basic-table th,
table.basic-table td {
  padding: 15px 28px;
}

table.basic-table tr:nth-child(odd) {
  background-color: #f6f6f6
}

table.basic-table {
  margin-bottom: 0;
}
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity = "sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin = "anonymous">
<script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity = "sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin = "anonymous"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity = "sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin = "anonymous"></script>


<table class = "basic-table treat-table research">

  <tr>
    <th>ID</th>
    <th>Category</th>
    <th>Treatment Name</th>
    <th>Price</th>
    <th>+</th>
  </tr>
 
  <!-- Row -->
  <tr class = "accordion">
    <td>1</td>
    <td>Plastic surgery</td>
    <td>Nose job</td>
    <td>from 2000$</td>
    <td>+</td>
  </tr>
  <tr class = "rowContent">
    <td colspan = "5">
    <h5>This is content</h5>
    <p>This area show hided content</p>
    </td>
  </tr>

</table>

Я редактирую его и меняю класс .research на .treat-table, теперь, пожалуйста, помогите мне, потому что он все равно не работает.

Reza 21.01.2019 12:06

Оставив HTML DOM и CSS одинаковыми, замените код jQuery на приведенный ниже code Надеюсь, это сработает.

$(function() {
    $('.rowContent').hide();
    $(".basic-table .accordion").click(function() {
       (".rowContent").not($(this).next()).hide();
        $(this).next(".rowContent").toggle();
    })
});

$(function() {
            $('.rowContent').hide();
            $(".basic-table .accordion").click(function(){
            $(".rowContent").not($(this).next()).hide();
                $(this).next(".rowContent").toggle();
            })
        });
table.basic-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  border: none;
  margin-bottom: 15px;
}

table.basic-table th {
  background-color: #66676b;
  text-align: left;
  color: #fff;
  vertical-align: top;
  font-weight: 500;
}

table.basic-table th:first-child {
  border-radius: 4px 0 0 4px;
}

table.basic-table th:last-child {
  border-radius: 0 4px 4px 0;
}

table.basic-table th,
table.basic-table td {
  padding: 15px 28px;
}

table.basic-table tr:nth-child(odd) {
  background-color: #f6f6f6
}

table.basic-table {
  margin-bottom: 0;
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity = "sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin = "anonymous"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity = "sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin = "anonymous"></script>


<table class = "basic-table treat-table">

  <tr>
    <th>ID</th>
    <th>Category</th>
    <th>Treatment Name</th>
    <th>Price</th>
    <th>+</th>
  </tr>
 
  <!-- Row -->
  <tr class = "accordion">
    <td>1</td>
    <td>Plastic surgery</td>
    <td>Nose job</td>
    <td>from 2000$</td>
    <td>+</td>
  </tr>
  <tr class = "rowContent">
    <td colspan = "5">
    <h5>This is content</h5>
    <p>This area show hided content</p>
    </td>
  </tr>
 <!-- Row -->
  <tr class = "accordion">
    <td>1</td>
    <td>Plastic surgery</td>
    <td>Nose job</td>
    <td>from 2000$</td>
    <td>+</td>
  </tr>
  <tr class = "rowContent">
    <td colspan = "5">
    <h5>This is content</h5>
    <p>This area show hided content</p>
    </td>
  </tr>


</table>
Please leave a comment if it doesnot work.

Другие вопросы по теме