简体   繁体   中英

use jquery hover from class method

I'm trying to use .hover method of jquery in a javascript class:

var test = {

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

};

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

but here this refers to class itself and not to eventObject .
How can I listen for events with jquery from a javascript class?

If you simply remove the parenthesis and the usage of the this keyword, jQuery will call your functions with the required variables as expected within the context of the element.

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();
});

You should be applying that to each element that is returned by your class query.

$("#elm li").each(function() {
    var $self = $(this);

    $self.hover(test.showTitle($self), test.hideTitle());
}

Wrap the call in an anonymous function that gives you access to e .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM