我有以下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/