javascript - 为什么 Bootstrap 工具提示没有初始化两次?

标签 javascript jquery html css twitter-bootstrap

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Bootstrap Example</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.js"></script>
</head>
<body>

	<div class="container">
		<h3>Tooltip Example</h3>
		<a  data-toggle="tooltip" title="Hooray!">Hover over me</a>
	</div>

	<script>
	$(document).ready(function(){
		$('[data-toggle="tooltip"]').tooltip();  
                $('[data-toggle="tooltip"]').off("mouseenter mouseleave");
		$('[data-toggle="tooltip"]').tooltip();

	});
	</script>

</body>
</html>

为什么即使我初始化了两次也无法获得工具提示??

最佳答案

DavidG 的评论与记录。基本上,如果您希望能够再次调用 tooltip 并让它附加监听器,则需要完全销毁 tooltip。通过调用 off,您只是删除了监听器,而不是破坏了 tooltip。因此,当您第二次调用 tooltip 时,它不会再次初始化 tooltip。因为下面一行:

if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))

https://github.com/twbs/bootstrap/blob/v3-dev/js/tooltip.js#L501

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Bootstrap Example</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.js"></script>
</head>
<body>

	<div class="container">
		<h3>Tooltip Example</h3>
		<a data-toggle="tooltip" data-placement="top" title="Hooray!">Hover over me</a>
	</div>

	<script>
	$(document).ready(function(){
            console.log("init");
            $('[data-toggle="tooltip"]').tooltip();
            setTimeout(function() {
                console.log("destroy");
                $('[data-toggle="tooltip"]').tooltip("destroy");
                setTimeout(function() {
                    console.log("reinit");
                    $('[data-toggle="tooltip"]').tooltip();
                }, 5000);
            }, 5000);
	});
	</script>

</body>
</html>

关于javascript - 为什么 Bootstrap 工具提示没有初始化两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42275025/

相关文章:

jquery - 制作跳转菜单(HTML 选择下拉菜单)的最佳方法是什么?

jQuery AJAX GET html 数据 IE8 不起作用

html - 根据浏览器大小的 Bootstrap 3 堆栈网格

javascript - 如何测试 google.maps.Geocoder?

javascript - 在 Node.js 中编写和加载模块的正确方法?

javascript - 使用 Shiny.onInputChange

javascript - 如何导出带有方法和属性的对象

javascript - 删除数据 jQuery

html - WordPress : Issues in CSS animations in Mobile

javascript - 通过 Kinetic.js 文本元素中的字符串索引获取单词/字符屏幕位置