我正在尝试扩展 Bootstrap 弹出窗口以在手动模式下退出时关闭。我正在尝试扩展弹出框类继承的工具提示类,如下所示:
/* WHY CANT I CALL the HIDE FUNCTION WHEN ESC key press is intercepted????
Why is the hide class undefined when the keypress is intercetped?
*/
!function ($) {
"use strict"
/* TOOLTIP PUBLIC CLASS DEFINITION
* =============================== */
var Tooltip = function (element, options) {
this.init('tooltip', element, options)
}
Tooltip.prototype = {
constructor: Tooltip
, init: function (type, element, options) {
//init logic here
$(document).keypress(function (e) {
if (e.which == 27) { this.hide };
}); ^^^^^^^^^^^^^
this.hide is undefined on debug????
}
, hide: function () {
//hide logic
}
}
最佳答案
您需要使用这个:
$tooltip = this;
$(document).keydown(function(e){
if (e.keyCode === 27)
$tooltip.hide();
});
你的问题是你想要的“this”实际上是文档并且它没有隐藏功能。当触发 keypress/keydown 事件时,函数内的“this”是触发事件的元素,因此是文档。请记住,JavaScript 具有函数作用域,这意味着在许多不同的函数内部时,您需要谨慎对待“this”变量。
关于jquery - bootstrap popover 添加 esc 按键检查并关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10003439/