在基于 bootstrap 3.5 的网站中,我们将在单击按钮时更改输入文本工具提示,在三秒钟内显示并删除工具提示。
<input type="text" id="sample" title="Tip">
<button name="change me" id="changeBtn">Change Tool Tip!</button>
//Initiall tooltip for all elements
$("[title!='']").tooltip();
$("#changeBtn").click(function () {
//Change tooltip text
$("#sample").attr('title', 'New Tip!').tooltip('fixTitle').tooltip('show');
//remove tooltipe after 3 sec
setTimeout(function () {
$(this).tooltip('destroy');
}, 3000)
})
问题是工具提示没有被破坏并继续显示。如果我将 $(this).tooltip('destroy');
更改为 $("[title!='']").tooltip('destroy');
它会起作用,但它不正确,因为它会删除所有其他工具提示。
有什么意见吗?
最佳答案
因为 this
的上下文在 setTimeout
中发生了变化,所以将 this
的副本保存到一个新变量中并改用它:
$("#changeBtn").click(function () {
var _this = this;
setTimeout(function () {
$(_this).tooltip('destroy');
}, 3000)
})
关于 scope and context here 的一些宝贵信息.
关于javascript - 三秒后隐藏 Bootstrap 工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33780338/