Можете ли вы разместить ссылку или кнопку внутри аккордеона MDB?

У меня есть кнопка внутри заголовков аккордеона (которые служат кнопками для открытия/закрытия элемента аккордеона).

Когда я нажимаю кнопку, вызывается базовый метод, но также открывается/закрывается аккордеон.

Можно как-то отключить функционал аккордеона для конкретной кнопки внутри?

Пример:

Редактор MDB

<div class = "accordion" id = "accordionExample">
  <div class = "card z-depth-0 bordered">
    <div class = "card-header" id = "headingOne">
      <h5 class = "mb-0">
        <button class = "btn btn-link" type = "button" data-toggle = "collapse" data-target = "#collapseOne"
          aria-expanded = "true" aria-controls = "collapseOne">
          Collapsible Group Item #1
          
          <a href = "javascript:alert('hi')" class = "ml-4">Test</a>
        </button>
      </h5>
    </div>
    <div id = "collapseOne" class = "collapse show" aria-labelledby = "headingOne"
      data-parent = "#accordionExample">
      <div class = "card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3
        wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum
        eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla
        assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
        nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer
        farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
        labore sustainable.
      </div>
    </div>
  </div>
  <div class = "card z-depth-0 bordered">
    <div class = "card-header" id = "headingTwo">
      <h5 class = "mb-0">
        <button class = "btn btn-link collapsed" type = "button" data-toggle = "collapse"
          data-target = "#collapseTwo" aria-expanded = "false" aria-controls = "collapseTwo">
          Collapsible Group Item #2
          
          <a href = "javascript:alert('hi')" class = "ml-4">Test</a>
        </button>
      </h5>
    </div>
    <div id = "collapseTwo" class = "collapse" aria-labelledby = "headingTwo" data-parent = "#accordionExample">
      <div class = "card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3
        wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum
        eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla
        assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
        nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer
        farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
        labore sustainable.
      </div>
    </div>
  </div>
  <div class = "card z-depth-0 bordered">
    <div class = "card-header" id = "headingThree">
      <h5 class = "mb-0">
        <button class = "btn btn-link collapsed" type = "button" data-toggle = "collapse"
          data-target = "#collapseThree" aria-expanded = "false" aria-controls = "collapseThree">
          Collapsible Group Item #3
          
          <a href = "javascript:alert('hi')" class = "ml-4">Test</a>
        </button>
      </h5>
    </div>
    <div id = "collapseThree" class = "collapse" aria-labelledby = "headingThree" data-parent = "#accordionExample">
      <div class = "card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3
        wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum
        eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla
        assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
        nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer
        farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
        labore sustainable.
      </div>
    </div>
  </div>
</div>

Что вы хотите отключить? Ссылка на тест?

Louys Patrice Bessette 09.12.2020 18:01
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Введение в CSS
Введение в CSS
CSS является неотъемлемой частью трех основных составляющих front-end веб-разработки.
Как выровнять Div по центру?
Как выровнять Div по центру?
Чтобы выровнять элемент <div>по горизонтали и вертикали с помощью CSS, можно использовать комбинацию свойств и значений CSS. Вот несколько методов,...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Ангулярный шаблон для бронирования путешествий
Toor - Travel Booking Angular Template один из лучших Travel & Tour booking template in the world. 30+ валидированных HTML5 страниц, которые помогут...
0
1
855
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Попробуй это Я удалил data-target = "#collapseTwo" на data-target = "#"

$(document).ready(function(){
  $('.test').click(function(){
    alert('I am Working!');
  });
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>



<div class = "accordion" id = "accordionExample">
  <div class = "card z-depth-0 bordered">
    <div class = "card-header" id = "headingOne">
      <h5 class = "mb-0">
        <button class = "btn btn-link" type = "button" data-toggle = "#" data-target = "#collapseOne"
          aria-expanded = "true" aria-controls = "collapseOne">
          Collapsible Group Item #1
          
          <a href = "javascript:alert('hi')" class = "ml-4">Test</a>
        </button>
      </h5>
    </div>
    <div id = "collapseOne" class = "collapse show" aria-labelledby = "headingOne"
      data-parent = "#accordionExample">
      <div class = "card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3
        wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum
        eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla
        assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
        nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer
        farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
        labore sustainable.
      </div>
    </div>
  </div>
  <div class = "card z-depth-0 bordered">
    <div class = "card-header" id = "headingTwo">
      <h5 class = "mb-0">
        <button class = "btn btn-link collapsed test" type = "button" data-toggle = "collapse"
          data-target = "#" aria-expanded = "false" aria-controls = "collapseTwo">
          Collapsible Group Item #2
          
          <a href = "javascript:alert('hi')" class = "ml-4">Test</a>
        </button>
      </h5>
    </div>
    <div id = "collapseTwo" class = "collapse" aria-labelledby = "headingTwo" data-parent = "#accordionExample">
      <div class = "card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3
        wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum
        eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla
        assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
        nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer
        farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
        labore sustainable.
      </div>
    </div>
  </div>
  <div class = "card z-depth-0 bordered">
    <div class = "card-header" id = "headingThree">
      <h5 class = "mb-0">
        <button class = "btn btn-link collapsed" type = "button" data-toggle = "collapse"
          data-target = "#collapseThree" aria-expanded = "false" aria-controls = "collapseThree">
          Collapsible Group Item #3
          
          <a href = "javascript:alert('hi')" class = "ml-4">Test</a>
        </button>
      </h5>
    </div>
    <div id = "collapseThree" class = "collapse" aria-labelledby = "headingThree" data-parent = "#accordionExample">
      <div class = "card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3
        wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum
        eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla
        assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
        nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer
        farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
        labore sustainable.
      </div>
    </div>
  </div>
</div>
Ответ принят как подходящий

Я предполагаю, что вы НЕ хотите иметь функциональность аккордеона на «тестовой» ссылке... Но все же хотите функциональность на остальной части кнопки.

Итак, для этой ссылки вам понадобится:

  • e.stopPropagation() чтобы событие клика не всплывало на кнопку
  • e.preventDefault() для предотвращения нормального поведения привязки

Затем я предлагаю вам использовать один обработчик событий, привязанный к классу, вместо какого-то встроенного JS. В моем примере вы можете увидеть, как определить, какая ссылка была нажата, и затем применить какое-то конкретное действие.

$(document).ready(function(){
  $(".test").click(function(e){
    e.stopPropagation()
    e.preventDefault()
  
    clickedHeader = e.target.closest(".card-header").id
    alert("Test link in #"+clickedHeader)
  })
})
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>


<div class = "accordion" id = "accordionExample">
  <div class = "card z-depth-0 bordered">
    <div class = "card-header" id = "headingOne">
      <h5 class = "mb-0">
        <button class = "btn btn-link" type = "button" data-toggle = "collapse" data-target = "#collapseOne"
          aria-expanded = "true" aria-controls = "collapseOne">
          Collapsible Group Item #1
          
          <a href = "#" class = "ml-4 test">Test</a>
        </button>
      </h5>
    </div>
    <div id = "collapseOne" class = "collapse show" aria-labelledby = "headingOne"
      data-parent = "#accordionExample">
      <div class = "card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3
        wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum
        eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla
        assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
        nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer
        farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
        labore sustainable.
      </div>
    </div>
  </div>
  <div class = "card z-depth-0 bordered">
    <div class = "card-header" id = "headingTwo">
      <h5 class = "mb-0">
        <button class = "btn btn-link collapsed" type = "button" data-toggle = "collapse"
          data-target = "#collapseTwo" aria-expanded = "false" aria-controls = "collapseTwo">
          Collapsible Group Item #2
          
          <a href = "#" class = "ml-4 test">Test</a>
        </button>
      </h5>
    </div>
    <div id = "collapseTwo" class = "collapse" aria-labelledby = "headingTwo" data-parent = "#accordionExample">
      <div class = "card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3
        wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum
        eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla
        assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
        nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer
        farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
        labore sustainable.
      </div>
    </div>
  </div>
  <div class = "card z-depth-0 bordered">
    <div class = "card-header" id = "headingThree">
      <h5 class = "mb-0">
        <button class = "btn btn-link collapsed" type = "button" data-toggle = "collapse"
          data-target = "#collapseThree" aria-expanded = "false" aria-controls = "collapseThree">
          Collapsible Group Item #3
          
          <a href = "#" class = "ml-4 test">Test</a>
        </button>
      </h5>
    </div>
    <div id = "collapseThree" class = "collapse" aria-labelledby = "headingThree" data-parent = "#accordionExample">
      <div class = "card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3
        wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum
        eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla
        assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred
        nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer
        farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
        labore sustainable.
      </div>
    </div>
  </div>
</div>

Спасибо! Именно то, что я искал

MauriceNino 11.12.2020 21:14

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