Кнопка DropBown Navbar в Javascript Вызов первой кнопки - PullRequest
0 голосов
/ 07 апреля 2020

В моей панели навигации первая кнопка работает, но следующие кнопки не работают.

Следующая кнопка вызывает только первую кнопку. Я также хочу, чтобы моя навигация реагировала на значок гамбургера. Я не могу понять возможное решение.

Я знаю, Javascript вызывает только первую кнопку, я хочу, чтобы Javascript вызывал последующие кнопки по классу.

Я не знаю, как подойти к этой проблеме. Некоторые решения, которые я просматривал, были только кнопки, но я хочу, чтобы кнопки нажимались внутри моей панели навигации. И некоторые другие решения имеют выпадающее меню на панели навигации, но они не закрываются при нажатии на самом меню, а закрываются при нажатии в окне

    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
    .navbar {
      overflow: hidden;
      background-color: #333;
      font-family: Arial, Helvetica, sans-serif;
    }

    .navbar a {
      float: left;
      font-size: 16px;
      color: white;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
    }

    .dropdown {
      float: left;
      overflow: hidden;
    }

    .dropdown .dropbtn {
      cursor: pointer;
      font-size: 16px;  
      border: none;
      outline: none;
      color: white;
      padding: 14px 16px;
      background-color: inherit;
      font-family: inherit;
      margin: 0;
    }

    .navbar a:hover, .dropdown:hover .dropbtn, .dropbtn:focus {
      background-color: red;
    }

    .dropdown-content {
      display: none;
      position: absolute;
      background-color: #f9f9f9;
      min-width: 160px;
      box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
      z-index: 1;
    }

    .dropdown-content a {
      float: none;
      color: black;
      padding: 12px 16px;
      text-decoration: none;
      display: block;
      text-align: left;
    }

    .dropdown-content a:hover {
      background-color: #ddd;
    }

    .show {
      display: block;
    }
    </style>
    </head>
    <body>

    <div class="navbar">
      <div class="dropdown">
      <button class="dropbtn" onclick="myFunction()">Upgrade 1
          <i class="fa fa-caret-down"></i>
      </button>
      <div class="dropdown-content" id="myDropdown">
        <a href="#" onclick="myFunc();">item 1</a>
        <a href="#">item 2</a>
        <a href="#">item 3</a>
      </div>
      </div> 


<div class="dropdown">
      <button class="dropbtn" onclick="myFunction()">Upgrade 2
          <i class="fa fa-caret-down"></i>
      </button>
      <div class="dropdown-content" id="myDropdown">
        <a href="#" onclick="myFunc();">item 1</a>
        <a href="#">item 2</a>
        <a href="#">item 3</a>
      </div>
      </div>

<div class="dropdown">
      <button class="dropbtn" onclick="myFunction()">Upgrade 3
          <i class="fa fa-caret-down"></i>
      </button>
      <div class="dropdown-content" id="myDropdown">
        <a href="#" onclick="myFunc();">item 1</a>
        <a href="#">item 2</a>
        <a href="#">item 3</a>
      </div>
      </div>


    </div>

    <h3>Dropdown Menu inside a Navigation Bar</h3>
    <p>Click on the "Dropdown" link to see the dropdown menu.</p>

    <script>

    function myFunc() {
      alert('You clicked a submenu item')
    }
    /* When the user clicks on the button, 
    toggle between hiding and showing the dropdown content */
    function myFunction() {
      document.getElementById("myDropdown").classList.toggle("show");
    }

    // Close the dropdown if the user clicks outside of it
    window.onclick = function(e) {
      if (!e.target.matches('.dropbtn')) {
      var myDropdown = document.getElementById("myDropdown");
        if (myDropdown.classList.contains('show')) {
          myDropdown.classList.remove('show');
        }
      }
    }
    </script>
    </body>
    </html>

Ответы [ 2 ]

0 голосов
/ 07 апреля 2020

Примечание 1 : удалить дубликаты идентификаторов. Никогда не используйте одинаковые идентификаторы для нескольких элементов. Примечание 2 : при использовании document.getElementById("myDropdown") будет возвращен только один элемент (& первый элемент). Примечание 3 : вместо 'ID' мы можем использовать класс. Пожалуйста, проверьте код ниже javascript, чтобы показать соответствующий раскрывающийся список.

//JS
function myFunction(event) {
  var clickedElement = event.target;
  console.log(clickedElement);
  if (clickedElement.nodeName != 'BUTTON') {
    clickedElement = clickedElement.parentElement;

  }
  var dropdownElement = clickedElement.nextElementSibling;
  dropdownElement.classList.add('tempClass'); //adding tempclass to avoid this in below loop

  var allOtherDropdowns = document.getElementsByClassName('dropdown-content');

  //close all other dropdowns
  for (var i = 0; i < allOtherDropdowns.length; i++) {
    if (!allOtherDropdowns[i].classList.contains('tempClass')) {
      allOtherDropdowns[i].classList.remove('show');
    }
  }
  dropdownElement.classList.toggle("show");
  dropdownElement.classList.remove('tempClass'); //removing the temp class here 
}
//HTML
<div class="dropdown">
      <button class="dropbtn" onclick="myFunction(event)">Upgrade 2
          <i class="fa fa-caret-down"></i>
      </button>
      <div class="dropdown-content">
        <a href="#" onclick="myFunc();">item 1</a>
        <a href="#">item 2</a>
        <a href="#">item 3</a>
      </div>
</div>

function myFunc() {
  alert('You clicked a submenu item')
}

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction(event) {
  var clickedElement = event.target;
  console.log(clickedElement);
  if (clickedElement.nodeName != 'BUTTON') {
    clickedElement = clickedElement.parentElement;

  }
  var dropdownElement = clickedElement.nextElementSibling;
  dropdownElement.classList.add('tempClass'); //adding tempclass to avoid this in below loop

  var allOtherDropdowns = document.getElementsByClassName('dropdown-content');

  //close all other dropdowns
  for (var i = 0; i < allOtherDropdowns.length; i++) {
    if (!allOtherDropdowns[i].classList.contains('tempClass')) {
      allOtherDropdowns[i].classList.remove('show');
    }
  }
  dropdownElement.classList.toggle("show");
  dropdownElement.classList.remove('tempClass'); //removing the temp class here
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn')) {
    var allDropdowns = document.getElementsByClassName('dropdown-content');

    //close all other dropdowns
    for (var i = 0; i < allDropdowns.length; i++) {
      allDropdowns[i].classList.remove('show');
    }
  }
}
.navbar {
  overflow: hidden;
  background-color: #333;
  font-family: Arial, Helvetica, sans-serif;
}

.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  cursor: pointer;
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navbar a:hover,
.dropdown:hover .dropbtn,
.dropbtn:focus {
  background-color: red;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

</head>

<body>

  <div class="navbar">
    <div class="dropdown">
      <button class="dropbtn" onclick="myFunction(event)">Upgrade 1
          <i class="fa fa-caret-down"></i>
      </button>
      <div class="dropdown-content">
        <a href="#" onclick="myFunc();">item 1</a>
        <a href="#">item 2</a>
        <a href="#">item 3</a>
      </div>
    </div>


    <div class="dropdown">
      <button class="dropbtn" onclick="myFunction(event)">Upgrade 2
          <i class="fa fa-caret-down"></i>
      </button>
      <div class="dropdown-content">
        <a href="#" onclick="myFunc();">item 1</a>
        <a href="#">item 2</a>
        <a href="#">item 3</a>
      </div>
    </div>

    <div class="dropdown">
      <button class="dropbtn" onclick="myFunction(event)">Upgrade 3
          <i class="fa fa-caret-down"></i>
      </button>
      <div class="dropdown-content">
        <a href="#" onclick="myFunc();">item 1</a>
        <a href="#">item 2</a>
        <a href="#">item 3</a>
      </div>
    </div>


  </div>

  <h3>Dropdown Menu inside a Navigation Bar</h3>
  <p>Click on the "Dropdown" link to see the dropdown menu.</p>

</body>

</html>
0 голосов
/ 07 апреля 2020
    function myFunction() {
        document.getElementById("myDropdown").classList.toggle("show");
        document.getElementById("myDropdown1").classList.remove("show");
        document.getElementById("myDropdown2").classList.remove("show");
    }

    function myFunction1() {
        document.getElementById("myDropdown1").classList.toggle("show");
        document.getElementById("myDropdown").classList.remove("show");
        document.getElementById("myDropdown2").classList.remove("show");
    }

    function myFunction2() {
        document.getElementById("myDropdown2").classList.toggle("show");
        document.getElementById("myDropdown1").classList.remove("show");
        document.getElementById("myDropdown").classList.remove("show");
    }


    // Close the dropdown if the user clicks outside of it
    window.onclick = function(e) {
        if (!e.target.matches('.dropbtn')) {
            var myDropdown = document.getElementById("myDropdown");
            var myDropdown1 = document.getElementById("myDropdown1");
            var myDropdown2 = document.getElementById("myDropdown2");
            if (myDropdown.classList.contains('show')) {
                myDropdown.classList.remove('show');
            }
            if (myDropdown1.classList.contains('show')) {
                myDropdown1.classList.remove('show');
            }
            if (myDropdown2.classList.contains('show')) {
                myDropdown2.classList.remove('show');
            }
        }
    }

Тот же Id - проблема, я думаю

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...