现在Bootstrap 5已经删除了jQuery的依赖性,我试图找到一种方法,在一段指定的时间后,只使用原始的Javascript自动关闭警报。下面是我到目前为止所想到的一个片段。毫无疑问,有一种方法可以优化它,或者可能是一种更好的方法。如果有,请告诉我。
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<div id="alertID" class="alert alert-success fade show mt-1" role="alert">
Alert text here!
</div>
<!-- Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
<!-- Autodismiss alert -->
<script type="text/javascript">
// Enable dismissal of an alert via JavaScript:
var alertList = document.querySelectorAll('.alert')
alertList.forEach(function(alert) {
new bootstrap.Alert(alert)
})
// Get the alert element
// var alertQs = document.querySelector('.alert') // This line would target all alerts on the page
var alertQs = document.querySelector('#alertID') // This line only targets the element with ID #alertID
// Create a Bootstrap alert instance
var bsAlert = bootstrap.Alert.getInstance(alertQs)
// Dismiss alert after specified amount of time in milliseconds
window.setTimeout(() => { bsAlert.close(); }, 2000);
</script>
</body>
</html>
1条答案
按热度按时间irlmq6kh1#
您只需要为每个警报添加一个属性,这样就可以在Javascript代码中检索它。