0

尝试调用一个函数“clickEvent()”并使用 jQuery 将一个带有箭头键属性的 obj 传递给它。但我没有达到这个功能。这是代码。谢谢。

请注意:我正在分叉现有代码,但将我的 arrowPress 事件添加到其中。因此,如果 (direction != null) 区域,一切都应该保持原样,以便文档准备就绪。

$(document).ready(function() {
    $('body').keyup(function(event) {
        var direction = null;

        // handle cursor keys
        if (event.keyCode == 37) {
            // slide left
            direction = 'prev';
        } else if (event.keyCode == 39) {
            // slide right
            direction = 'next';
        }

        if (direction != null) {
            //alert($('.'+ direction).attr('rel'));
            //need to pass the alert above as an obj to the function clickEvent() below.
        }
    });

}); //end $(document).ready


//function on external .js src
(function($) {
    function clickEvent(obj) {
        alert(obj.attr("rel"));
    }

    $.fn.slidingPage = function(options) {
        $el = $(this);
    }
})(jQuery); //end ext js scr
4

3 回答 3

0

该函数clickEvent在另一个函数的作用域内,将它们放入相同的作用域或更高的作用域:

function clickEvent(obj) {
    alert(obj.attr("rel"));
}

$.fn.slidingPage = function(options) {
    var $el = $(this);
};

(function($) {
    $('body').keyup(function(event) {
        var direction = null;

        // handle cursor keys
        if (event.keyCode == 37) {
            // slide left
            direction = 'prev';
        } else if (event.keyCode == 39) {
            // slide right
            direction = 'next';
        }

        if (direction != null) {
            clickEvent( $('.'+ direction) );
        }
    });

});

没有理由将clickEventandslidingPage声明放在文档就绪处理程序中。

于 2012-10-24T10:38:16.327 回答
0

感谢安德烈·库兹明……

if (direction != null) {

   $('.'+ direction).click();       

}
于 2012-10-24T13:58:45.180 回答
0

如果您需要将代码包装到匿名函数中以防止全局变量污染,那么您的事件和函数代码应该放在同一范围内。

您可能需要在 .prev 和 .next 上触发点击事件。

$(document).ready(function() {
    $('body').keyup(function(event) {
        var direction = null;

        // handle cursor keys
        if (event.keyCode == 37) {
            // slide left
            direction = 'prev';
        } else if (event.keyCode == 39) {
            // slide right
            direction = 'next';
        }

        if (direction != null) {
            $('.'+ direction).click()
        }
    });

}); //end $(document).ready
于 2012-10-24T11:02:28.400 回答