简体   繁体   English

如何使用纯 JavaScript 在 Bootstrap 4 中初始化工具提示? 无 jQuery

[英]How to initialize Tooltips in Bootstrap 4 with pure JavaScript? No jQuery

I'm somehow stuck with this code:我不知何故被这段代码困住了:

$(function () {
  $('[data-toggle="tooltip"]').tooltip()
});

I'd like to change it to pure JavaScript.我想把它改成纯JavaScript。 I'm not sure how to call the tooltip function, I already have some ideas like:我不确定如何调用工具提示 function,我已经有了一些想法,例如:

var tooltips = document.querySelectorAll("[data-toggle='tooltip']");
for(var i = 0; i < tooltips.length; i++){
   //this gives an error
   tooltips[i].tooltip();
}

I'm able to get all the tooltips, but I cannot initialize them.我能够获得所有工具提示,但我无法初始化它们。 If I write something like this:如果我写这样的东西:

$(tooltips[i]).tooltip();

Then it works, but I want to remove the jQuery dependency since this is the only jQuery section that I have.然后它可以工作,但我想删除 jQuery 依赖项,因为这是我拥有的唯一 jQuery 部分。 Any idea?任何想法? I've been searching and I cannot find anything useful.我一直在寻找,我找不到任何有用的东西。

This code worked for me.这段代码对我有用。 (Inspired by bootstrap 5) (受引导程序 5 启发)

var tooltipElementList = document.querySelectorAll('[data-toggle="tooltip"]');
for (var x = 0; x < tooltipElementList.length; x++) {
    new bootstrap.Tooltip(tooltipElementList[x]);
}

For the new Bootstrap 5 , this will be the new option without jQuery:对于新的Bootstrap 5 ,这将是没有 jQuery 的新选项:

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})

More info: https://getbootstrap.com/docs/5.0/components/tooltips/更多信息: https://getbootstrap.com/docs/5.0/components/tooltips/

You can select all the elements with the data-toggle attribute you want like so:您可以 select 使用您想要的 data-toggle 属性的所有元素,如下所示:

    let tooltips = document.querySelectorAll('[data-toggle="tooltip"]')
    tooltips.forEach(tooltip => tooltip.tooltip())

And then loop through the resulting nodelist and then execute the method you want on each element.然后遍历生成的节点列表,然后在每个元素上执行您想要的方法。

However, this won't work for your particular use case, because the Bootstrap plugins rely on jQuery.但是,这不适用于您的特定用例,因为 Bootstrap 插件依赖于 jQuery。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM