javascript - How to construct a bootstrap dropdown list with static placeholder and custom icon
问题描述
I'm very new to web development and I'm trying to construct a dropdown list that contains a static, slightly greyed out, placeholder and a custom icon. When an item in the drop down list is selected, the text of the selected item should be displayed on the dropdown. I have tried a few different approaches and the code below gets me somewhat close but still not exactly what I'm looking for and I'm also not even sure if this is the right approach.
Is there a way to create a bootstrap (or non bootstrap) dropdown with a static placeholder, custom icon, and updates display text to user selection?
<div>
<label type = "button">Fruit</label>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Apple</a>
<a class="dropdown-item" href="#">Blueberry</a>
<a class="dropdown-item" href="#">Pear</a>
</div>
</div>
</div>
解决方案
请将此片段视为可能的答案。
$(".dropdown-item").click(function(){
$(".dropdown-item").removeClass("active");
$("#dropdownMenuLabel").text(this.innerHTML);
$(this).addClass("active");
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="text-dark">Fruit</span> <span id="dropdownMenuLabel"></span>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Apple</a>
<a class="dropdown-item" href="#">Blueberry</a>
<a class="dropdown-item" href="#">Pear</a>
</div>
</div>
推荐阅读
- c# - 使用 Moq 模拟复杂的泛型方法
- javascript - 如何在 React 中获取和显示 JSON?
- xamarin - 如何在 xamarin ios 中实现每 x 秒运行一次的服务
- sql - 使用 UTC 日期时间列创建 sql 表
- javascript - 如何解决这个问题 Click bug with an audio ProgressBar in javascript?
- arrays - 如何快速确定并从带有数组的结构中提取正确的数据
- ruby - 递归列出文件或目录时避免“检测到堆栈粉碎”
- android-studio - 从导入建议中排除颤振导出
- .htaccess - 如何将网站中的 www 替换为 my、m 等其他词?
- client - kcadm 创建的客户端总是未经授权的