多个按钮调用同一个 Bootstrap toast

问题描述 投票:0回答:1

只需调用一个 Bootstrap toast,使用唯一的 id,我就可以做到。但是:

  1. 我会有多个按钮,所有按钮都引用同一个 Toast 消息。我想触发一下,班级电话会议?在我的 JS 脚本中。我不知道如何称呼他们为班级。

    我知道,我无法通过 id 给他们打电话 (

    getElementById
    )。因为id必须是唯一的。因此缩短了我的问题以使其更加清晰:许多按钮为 1 以及相同的 Bootstrap toast 消息。

  2. Bootstrap 示例中的方法通过

    id=""
    触发,那么每个 id 都必须是唯一的。我怎样才能为我想要触发的所有 id 列出一个列表?因此,如果我要调用唯一的 id“”,它必须在脚本中给出一个来自变量的映射或循环,好吗?

也许我在 Bootstrap 网站上看到了一些解释,如何将按钮分组到一条 toast 消息。

这是我来自 Bootstrap 站点的示例代码: 按钮

<button type="button" class="btn btn-primary" id="id1ToAList">Show live toast</button>
<button type="button" class="btn btn-primary" id="id2ToAList">Show live toast</button>
<button type="button" class="btn btn-primary" id="id3ToAList">Show live toast</button>

容器的div:


<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <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">Bootstrap</strong>
      <small>11 mins ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
  </div>
</div>

我将使用 JS 脚本触发所有内容,作为要执行或映射的 id 的给定列表。

做了一些实验

const toastTrigger = document.querySelectorAll('*[id]')


<script>
const toastTrigger = document.getElementById('trigger my list here') // or trigger as a class all buttons to one toast message
const toastLiveExample = document.getElementById('liveToast')

if (toastTrigger) {
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
toastTrigger.addEventListener('click', () =\> {
toastBootstrap.show()
})
}
</script>
javascript twitter-bootstrap toast
1个回答
0
投票

这似乎源于对如何添加事件监听器的误解。 您需要做的就是添加多个事件侦听器 - 每个按钮一个。

const toastTrigger1 = document.getElementById('id1ToAList')
const toastTrigger1 = document.getElementById('id2ToAList')
const toastTrigger1 = document.getElementById('id3ToAList')

const toastLiveExample = document.getElementById('liveToast')

if (toastTrigger1) {
  const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
  toastTrigger.addEventListener('click', () =\> {
    toastBootstrap.show()
  })
}

if (toastTrigger2) {
  const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
  toastTrigger2.addEventListener('click', () =\> {
    toastBootstrap.show()
  })
}

if (toastTrigger3) {
  const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
  toastTrigger3.addEventListener('click', () =\> {
    toastBootstrap.show()
  })
}

© www.soinside.com 2019 - 2024. All rights reserved.