通过调用 javascript class 方法显示 bootstrap toast

show bootstrap toast by calling javascript class method

我想通过这样的调用来表示bootstrap敬酒:

let my_toast = new myToast('title', 'hello world');
my_toast.show();

到目前为止,我正在从外部文件加载 html myToast.html:

  <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
<div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
    <img src="" class="rounded me-2" alt="">
    <strong class="me-auto">
      <div id="toast-title">
        Bootstrap
      </div>
    </strong>
    <small><div id=""></div></small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div id="toast-body" class="toast-body">
        Hello, world! This is a toast message.
    </div>
</div>
</div>

并将其添加到主页上的 <div id="mydiv"></div>,更改标题和 body 并调用 Tost.show() 方法:

<script>
    class myToast{
        toast_html; 

        constructor(title, message) {
            this.title = title;
            this.message = message;
            
            let template_html;
            $.ajax({
                async: false, // resume if finished
                type: 'GET',
                url: "myToast.html",
                success: function(data) {
                    template_html = data;
                }
            });

            console.log("var html: " + html); 

            let toast_div = document.createElement("div");
            toast_div.id = "toast_wrapper";              
            toast_div.innerHTML = template_html;            
            toast_div.querySelector("#toast-title").innerHTML = (this.title);
            toast_div.querySelector("#toast-body").innerHTML = (this.message);

            this.toast_html = toast_div;
        }
    }

    let to = new myToast('title', 'hello world');
    $("#mydiv").append(to.toast_html);

    var toastLiveExample = document.getElementById('liveToast');
    var toast = new bootstrap.Toast(toastLiveExample);

    toast.show();
</script>

有better/shorter解决方案吗?

您可以将您的 HTML 模板代码转移到您的 JavaScript,这样您就不会额外 ajax 调用外部 HTML 模板。通过这种方式,您还可以添加对 toast 布局的更改(也许您想要危险、成功、信息或警告 toast 类型)。诀窍是在 Toast class.

初始化期间创建元素

我将提供您可以在下面测试的实现。

参考:Bootstrap 5 Toast - getOrCreateInstance

/* Implementation */
function Toast(title, description) {
    var toastElement = buildToast(title, description);
    var toastWrapper = getOrCreateToastWrapper();
    toastWrapper.append(toastElement);
    this.bootstrapToast = bootstrap.Toast.getOrCreateInstance(toastElement);
    
    this.show = function() {
        this.bootstrapToast.show();
    }
    
    this.hide = function() {
        this.bootstrapToast.hide();
    }
    
    this.dispose = function() {
        this.bootstrapToast.dispose();
    }
}

/* Example CTA */
var title = 'Bootstrap';
var description = 'Hello, world! This is a toast message.';
var toast = new Toast(title, description);
toast.show();

/* Utility methods */
function getOrCreateToastWrapper() {
    var toastWrapper = document.querySelector('body > [data-toast-wrapper]');
    
    if (!toastWrapper) {
        toastWrapper = document.createElement('div');
        toastWrapper.style.zIndex = 11;
        toastWrapper.style.position = 'fixed';
        toastWrapper.style.bottom = 0;
        toastWrapper.style.right = 0;
        toastWrapper.style.padding = '1rem';
        toastWrapper.setAttribute('data-toast-wrapper', '');
        document.body.append(toastWrapper);
    }
    
    return toastWrapper;
}

function buildToastHeader(title) {
    var toastHeader = document.createElement('div');
    toastHeader.setAttribute('class', 'toast-header');
    
    var img = document.createElement('img');
    img.setAttribute('class', 'rounded me-2');
    img.setAttribute('src', '');
    img.setAttribute('alt', '');
    
    var strong = document.createElement('strong');
    strong.setAttribute('class', 'me-auto');
    strong.textContent = title;
    
    var closeButton = document.createElement('button');
    closeButton.setAttribute('type', 'button');
    closeButton.setAttribute('class', 'btn-close');
    closeButton.setAttribute('data-bs-dismiss', 'toast');
    closeButton.setAttribute('data-label', 'Close');
    
    toastHeader.append(img);
    toastHeader.append(strong);
    toastHeader.append(closeButton);

    return toastHeader;
}

function buildToastBody(description) {
    var toastBody = document.createElement('div');
    toastBody.setAttribute('class', 'toast-body');
    toastBody.textContent = description;
    
    return toastBody;
}

function buildToast(title, description) {
    var toast = document.createElement('div');
    toast.setAttribute('class', 'toast');
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    
    var toastHeader = buildToastHeader(title);
    var toastBody = buildToastBody(description);
    
    toast.append(toastHeader);
    toast.append(toastBody);
    
    return toast;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>