jquery - bootstrap popover 添加 esc 按键检查并关闭

标签 jquery closures twitter-bootstrap popover

我正在尝试扩展 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/

相关文章:

php - 使用 Composer 和 Assets 将 jQuery 包含在 symfony 项目中的最佳方法是什么

python - 局部范围,超出封闭范围

ios - 'finish in' 在 Swift 中是什么意思?

javascript - 以模态形式返回 View

css - Link DropDown Bootstrap 无法正常工作

javascript - 为什么 $ ('a.current' ).removeClass ('current' );不管用?

javascript - 破坏bootbox

javascript - 这是 Javascript Closure 用例吗?

angular - 如何在 Angular 11 组件 TS 中使用 Bootstrap 5 JS

javascript - jQuery 隐藏表格行