如何在Bootstrap工具提示中添加标签表

时间:2020-08-28 11:03:24

标签: bootstrap-4 tooltip

我按如下方式初始化对象

$('[data-toggle="tooltip"]').tooltip({
    container: 'body',
    html: true,
    title: function () {
        return '<u>text1</u><table class="table"><tr><td>text2</td></tr></table>';
    }
});

但是我只看到text1。 可以在工具提示中插入表格吗?

2 个答案:

答案 0 :(得分:0)

我相信工具提示的内容会添加到您要在其上应用工具提示的元素的title属性。要分解它,本质上您想做的是...

<div data-toggle="tooltip" title="<u>text1</u><table class="table"><tr><td>text2</td></tr></table>">
Foo
</div>

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

如果要在表格中包含信息作为工具提示,我认为您必须创建一个包含表格的元素,将其正确放置在要悬停的元素附近,并使用$ .hover显示和隐藏元素。类似于

$('#hoverTest').hover(function(){
  $('#customTooltip').removeClass('hideme');
}, function(){
  $('#customTooltip').addClass('hideme');
});
table, th, td {
  border: 1px solid black;
}

.hideme{
  display:none
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hoverTest">Hover here</div>
<div id="customTooltip" class="hideme">
  <table>
    <th>Col1</th>
    <th>Col2</th>
    <tr>
      <td>Cell1</td>
      <td>Cell2</td>
    </tr>
   </table>
 </div>

答案 1 :(得分:0)

我发现issue on Github指出Bootstrap's sanitizer会导致此问题。

您需要做的是在白名单中允许用于表的所有元素(也是tbody,这不是您的代码定义的,但似乎您需要它)。还请看一下question,它是在弹出窗口中完成的。之后,您可以再次在tooltip选项中使用此自定义白名单。

我创建了一个running fiddle

var myDefaultWhiteList = $.fn.tooltip.Constructor.Default.whiteList;
myDefaultWhiteList.table = ['class'];
myDefaultWhiteList.tbody = [];
myDefaultWhiteList.tr = [];
myDefaultWhiteList.td = [];

$('[data-toggle="tooltip"]').tooltip({
  container: 'body',
  html: true,
  whiteList: myDefaultWhiteList,
  title: function () { return '<u>text1</u><table class="table text-light"><tr><td>text2</td></tr></table>'; }
});
<script src="https://code.jquery.com/jquery-3.4.1.slim.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>
<button class="ml-5 mt-5 btn btn-primary" data-toggle="tooltip">
  Test
</button>

您可能会注意到,这是Bootstrap不建议的行为。我建议将Bootstrap's popovers用于较大的内容,例如表格。

祝你好运!