我已经实现了导航栏,以及如何首先使用javascript显示所选选项



function getoptions(){
  var x =document.getElementById("languagelist");
  var y = document.getElementById("language");
  y.innerHTML= // set the selected language
}

<nav>
    <div class="dropdown">
        <button id="language" class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown"
                aria-haspopup="true" aria-expanded="false">
                English
        </button>
        <div id="languagelist" class="dropdown-menu" aria-labelledby="dropdownMenu2" onclick="getoptions()">
            <a class="dropdown-item" href="/en">English</a>
            <a class="dropdown-item" href="/fr">French</a>
        </div>
    </div>
</nav>

最佳答案

这种纯JavaScript解决方案将为您工作。运行并测试




<html>

<head>
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

  <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>

<body>
  <nav>
    <div class="dropdown">
      <button id="language" class="btn btn-warning dropdown-toggle" type="button" id="dropdownMenu2"
        data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="clickButton()">
        English
      </button>
      <div id="languagelist" class="dropdown-menu" aria-labelledby="dropdownMenu2" onclick="clickItem(); return false">
        <a class="dropdown-item" href="/en">English</a>
        <a class="dropdown-item" href="/fr">French</a>
      </div>
    </div>
  </nav>
</body>

<script>

  function clickButton() {
    document.getElementById("languagelist").click();
  }

  function clickItem() {
    var element = document.getElementById("languagelist");
    for (var i = 0; i < element.children.length; i++) {
      (function(index) {
        element.children[i].onclick = function() {
          var thetext = element.getElementsByTagName('a')[index].innerHTML;
          // var thehref = element.getElementsByTagName('a')[index].href; get the href here once you hosted, for testing I will use the name
          var buttonelement = document.getElementById("language");
          buttonelement.innerText = thetext;
          window.open("/"+thetext);
        }
      })(i);
    }
  }

</script>

</html>





希望这对某人有帮助。干杯!

09-30 18:27