【问题标题】:Trying to get the Bootstrap dropdown button text to change to the item selected试图让 Bootstrap 下拉按钮文本更改为所选项目
【发布时间】:2020-08-28 05:50:36
【问题描述】:

我正在使用引导程序来设置下拉按钮的样式,并且我希望将按钮文本更改为从下拉列表中选择的任何项目。我猜 JavaScript 是实现这一目标的最佳方式,但我对它还不是很熟悉。任何帮助将不胜感激。
这是我的第一个下拉按钮的 html。谢谢

    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      Genre
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenu1">
      <button class="dropdown-item" type="button">Adventure</button>
      <button class="dropdown-item" type="button">Sci-Fi</button>
      <button class="dropdown-item" type="button">Comedy</button>
    </div>

【问题讨论】:

  • 您猜对了:需要一些 javascript。没什么大不了的。现在虽然我没有看到代码尝试。您是否希望有一个随机的完整解决方案?
  • 下拉菜单更像是一个菜单。听起来你真的想在这里使用选择。只是我的 2 美分
  • 是的,我尝试了一些不起作用的方法,也没有考虑将它们包括在内。下次我寻求帮助时,我会将我的尝试包括在内。

标签: javascript html button bootstrap-4


【解决方案1】:

@finiteloop 感谢您的帮助。根据您向我指出的方向,我为每个下拉元素添加了一个 onclick 事件,并添加了以下函数来满足我的需要:

<div class="dropdown mx-3">
    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      Genre
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenu1">
      <button class="dropdown-item" type="button" onclick="showGenre(this)">Adventure</button>
      <button class="dropdown-item" type="button" onclick="showGenre(this)">Sci-Fi</button>
      <button class="dropdown-item" type="button" onclick="showGenre(this)">Comedy</button>
    </div>
  </div>
function showGenre(item) {
  document.getElementById("dropdownMenu1").innerHTML = item.innerHTML;
}

【讨论】:

  • 不错!很高兴能帮上忙!
【解决方案2】:

@MasterShake20 你可以做这样的事情并将其集成到你的代码中:

<!DOCTYPE html>
<html>
<body>

<form>
  Select your favorite fruit:
  <select id="mySelect">
    <option value="apple">Apple</option>
    <option value="orange">Orange</option>
    <option value="pineapple">Pineapple</option>
    <option value="banana">Banana</option>
  </select>
</form>

<p>Click the button to change the selected fruit to banana.</p>

<button id="btnTxt" type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  
let buttonVal = document.getElementById("mySelect").value;
document.getElementById('btnTxt').innerHTML = buttonVal;
  
}
</script>

</body>
</html>

在此处查看其工作原理: https://www.w3schools.com/code/tryit.asp?filename=GI7I2WCF1N82

这并不完全是您想要做的事情,但它可以为您指明正确的方向并让您了解需要发生的事情。

另外,如果您刚刚开始,W3 是一个很好的资源,所以在这里查看他们的 JavaScript 教程: https://www.w3schools.com/js/default.asp :D

【讨论】:

  • 谢谢,我会查看您提供的链接,以便更好地了解如何完成我正在寻找的内容。
  • @MasterShake20 这听起来是个好计划!如果您发现这对您有帮助,您会考虑将我的答案标记为正确吗? :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-14
相关资源
最近更新 更多