繁体   English   中英

Javascript - 使元素可点击并关闭其他按钮

[英]Javascript - Make element clickable and toggle off other button

如何使加号/减号可点击? 现在不是...当我单击第二个按钮时,如果打开另一个按钮,如何关闭(下拉)?

爪哇脚本

$(".dropbtn").append('<span class="adl-signs">&nbsp;+</span>');

function ctaDropMenu(e) {
  e.target.nextElementSibling.classList.toggle("show");
}

function toggleSigns(e) {
  $(e.target).find('.adl-signs').html(function(_, html) {
    return $.trim(html) == '&nbsp;+' ? '&nbsp;-' : '&nbsp;+';
  });
}

$(".dropbtn").click( function(e) {
  ctaDropMenu(e)
  toggleSigns(e)
});

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

小提琴 = https://jsfiddle.net/neuhaus3000/jf1zetLw/8/

这是更新的小提琴 我试图尽可能地简化您的代码,并尽可能使用 jQuery。

function changeText(text) {
  return (text.indexOf('+') >= 0) ? 'Click Me -' : 'Click Me +';
}

$(".dropbtn").click(function() {

  var $this = $(this),
    $dropdownActive = $('.dropdown-active');

  /* changing the text of the active button (if any) */
  $dropdownActive.text(changeText($dropdownActive.text()));

  /* hiding the content under the active button (if any) */
  $('.dropdown-content', $dropdownActive.parent()).toggle('show');

  if (!$this.hasClass('dropdown-active')) {

    /* changing the text of the clicked button */
    $this.text(changeText($this.text()));

    /* showing the content under the clicked button */
    $('.dropdown-content', $this.parent()).toggle('show');

    /* adding this class to the clicked button */
    $this.addClass('dropdown-active');
  }

  /* removing this class from the active button */
  $dropdownActive.removeClass('dropdown-active');
});

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var $dropdownActive = $('.dropdown-active');

    /* changing the text of the active button (if any) */
    $dropdownActive.text(changeText($dropdownActive.text()));

    /* hiding the content under the active button (if any) */
    $('.dropdown-content', $dropdownActive.parent()).toggle('show');

    /* removing this class from the active button */
    $dropdownActive.removeClass('dropdown-active');
  }
}

如果您有任何麻烦,请告诉我。 谢谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM