JS和JQuery,将参数传递给函数

JS and JQuery, passing arguments to functions

本文关键字:参数传递 函数 JQuery JS      更新时间:2023-09-26

所以我刚开始制作一个更改的网页,我想为一些按钮等设置动画。所以我想写一个函数,它接受一个对象(在本例中为an)并为悬停事件声明函数。该功能在这个(非完整)版本中运行得很好:

    function hoverOver() {
        $(document).ready(function(){
            $("#FormA").hover(function(){
                $("#ButtonA").animate({marginLeft:"5px", opacity:"1"}, "fast");
            }, function(){
                $("#ButtonA").animate({marginLeft:"0px", opacity:"0.5"}, "fast");
            });
        });

但为了在多个按钮上使用该功能,我想这样写:

    function hoverOver(source) {    
        $(document).ready(function(){
            source.parent().hover(function(){
                source.animate({marginLeft:"5px", opacity:"1"}, "fast");
            }, function(){
                source.animate({marginLeft:"0px", opacity:"0.5"}, "fast");
            });
        });
    }
    // this is how I want to call the function with multiple Buttons
    hoverOver($("#ButtonA"));

我还强调,如果我将源变量传递给所有这样的函数,它就会起作用:

    function hoverOver(source) {
        $(document).ready(function(source){ //  <-- here
            source.parent().hover(function(source){ //  <-- here
                source.animate({marginLeft:"5px", opacity:"1"}, "fast");
            }, function(source){ // <-- and here
                source.animate({marginLeft:"0px", opacity:"0.5"}, "fast");
            });
        });
    }
    // this is how I want to call the function with multiple Buttons
    hoverOver($("#ButtonA"));

那么我的问题在哪里呢?我知道这种编码JS的方式不是最好的方式,特别是JS、HTML和CSS,有一百万种方法可以做到这一点,但我实际上是4天前开始的。)

感谢

如果你使用jQuery,你还可以扩展它的原型,比如:

$.fn.hoverOver = function(){
    this.each(function(){
        var $this = $(this);
        $this.parent().hover(function(){
             $this.animate({marginLeft:"5px", opacity:"1"}, "fast"); 
        }, function(){
             $this.animate({marginLeft:"0", opacity:"0.5"}, "fast"); 
        });
    });
}

然后将它绑定到任何类似的元素;

$("#buttonA").hoverOver();

或者这个:

$(".buttonHover").hoverOver();