我有以下 HTML,
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="dropdown">
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
Dropdown button
</button>
<div id="custom" class="dropdown-menu">
<a class="dropdown-item" href="#">Normal</a>
<a class="dropdown-item" href="#">Active</a>
<a class="dropdown-item" href="#">Disabled</a>
</div>
</div>
</div>
<script>
document.getElementById('custom').addEventListener("click", myFunction);
function myFunction() {
alert(this.textContent);
}
</script>
</body>
</html>
我正在尝试 alert
并设置button
文本到 drop-down
中选择的内容.
我可以通过将 id 设置为 dropdown-item
来获取该值并用JS读取它。但是我有n个dropdown-item
,所以添加id是不可行的。
jQuery
中有可用的解决方案但我怎样才能在不使用 jQuery
的情况下做到这一点? 。 ?
最佳答案
您可以访问目标元素的 innerHTML
或 innerText
属性:
document.getElementById('custom').addEventListener("click", myFunction);
function myFunction(e) {
alert(e.target.innerText);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">
<div class="dropdown">
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
Dropdown button
</button>
<div id="custom" class="dropdown-menu">
<a class="dropdown-item" href="#">Normal</a>
<a class="dropdown-item" href="#">Active</a>
<a class="dropdown-item" href="#">Disabled</a>
</div>
</div>
</div>
关于javascript - 显示下拉列表中选择的内容 : Bootstrap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57054715/