【问题标题】:use jquery hover from class method从类方法中使用jquery hover
【发布时间】:2014-01-27 23:01:52
【问题描述】:

我正在尝试在 javascript 类中使用 jquery 的 .hover 方法:

var test = {

    init:function(){
        $("#elm li").hover(test.showTitle(this), test.hideTitle());
    },
    showTitle:function(e){
        ...
    },
    hideTitle: function(){
        ...
    }

};

$(document).ready(function() {
    test.init();
});

但这里this 指的是类本身而不是eventObject。
如何使用 javascript 类中的 jquery 侦听事件?

【问题讨论】:

  • 你尝试过绑定而不是直接悬停吗?

标签: javascript jquery class events hover


【解决方案1】:

如果您只是删除括号和 this 关键字的使用,jQuery 将在元素的上下文中按照预期使用所需的变量调用您的函数。

var test = {

    init:function(){
        $("#elm li").hover(test.showTitle, test.hideTitle);
    },
    showTitle:function(e){
        console.log(e)
        console.log(this);
    },
    hideTitle: function(){
    }

};

$(document).ready(function() {
    test.init();
});

【讨论】:

    【解决方案2】:

    您应该将其应用于类查询返回的每个元素。

    $("#elm li").each(function() {
        var $self = $(this);
    
        $self.hover(test.showTitle($self), test.hideTitle());
    }
    

    【讨论】:

      【解决方案3】:

      将调用封装在一个匿名函数中,让您可以访问e。

      #("elm li").hover(function(e) {
          test.showTitle(e); //or this
      }, function(e) {
         test.hideTitle(e); //or this
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-05
        • 2011-07-27
        • 2015-09-02
        • 2020-07-17
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 2014-11-14
        相关资源
        最近更新 更多