Trang chủ / Bootstrap / Phương thức dispose()

Phương thức dispose()

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dispose Bootstrap Alerts via JavaScript</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    var btn = document.getElementById("myBtn");
    var element = document.getElementById("myAlert");
  
  	// Create alert instance
  	var myAlert = new bootstrap.Alert(element);
  	console.log(myAlert);
    // {_element: div#myAlert.alert.alert-info.alert-dismissible.fade.show}

    btn.addEventListener("click", function(){
        myAlert.dispose();
        console.log(myAlert);
        // {_element: null}
    });
});
</script>
</head>
<body>
<div class="m-4"> 
    <div id="myAlert" class="alert alert-info alert-dismissible fade show">
        <strong>Note!</strong> Press the "Dispose Alert" to destroy this alert.
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  	<button type="button" class="btn btn-danger" id="myBtn">Dispose Alert</button>
</div>
</body>
</html>

Xem ví dụ

 

Thấy bài viết hữu ích?

Ủng hộ tác giả để có thêm nhiều bài viết chất lượng nhé!

Tư vấn lộ trình CNTT 🤖