向元素添加多个事件

时间:2015-11-27 07:38:17

标签: javascript jquery events

假设我有以下代码:

function addScrollEvent(scrollElement, direction) { 
    $(scrollElement).mouseover(function(){
        var maxStreckeY = $("#viewport div").height() - $("#viewport").innerHeight();
        var currentPos = $("#viewport").scrollTop();
        if (direction == "down") {
            var restStrecke = maxStreckeY - currentPos;
            var timer = restStrecke / maxStreckeY *  namespace.config.autoScrollSpeed;
            $(element).stop().animate({scrollTop: maxStreckeY}, timer);
        }
        if (direction == "right") {
            var width = $("#viewport div").width();
            $(element).stop().animate({scrollLeft: width - $("#viewport").innerWidth()}, namespace.config.autoScrollSpeed);
        }
        if (direction == "up") {
            var timer = currentPos / maxStreckeY *  namespace.config.autoScrollSpeed;
            $(element).stop().animate({scrollTop: 0}, timer);   
        }
        if (direction == "left") {
            $(element).stop().animate({scrollLeft: 0}, namespace.config.autoScrollSpeed);
        }
    });

    $(scrollElement).mouseleave(function(){
        $(element).stop();
        checkScrollElements();
    });

如何将多个事件附加到scrollElement?我想在tabhold(在鼠标悬停部分)以及tableave(在mouseleave部分)执行确切的代码

我已经尝试过这样的事情:

$(scrollElement).on("mouseover tabhold", function(){
    ... the function
});

由于控制台给了我以下错误,因此无法正常工作:

"on is not a function" 

有人为此获得了解决方案,而没有为另一个事件块复制相同的代码吗? 提前致谢

1 个答案:

答案 0 :(得分:1)

您的on解决方案是正确的;问题是你正在使用过时的jQuery副本。 v1.6已经过了v1.7 四年前的过时。升级到最新版本。

如果由于某种原因你不能,那么旧功能是bind

$(scrollElement).bind("mouseover tabhold", function(){
    ... the function
});

另一种选择是单独编写函数,为其命名,并使用该名称。其中一个优点是,如果需要,它允许您将该功能与其他功能结合使用。

相关问题