简体   繁体   English

如何在不同的范围内重用变量?

[英]How can I reuse a variable in a different scope?

I am trying to figure out how I can reuse a variable within a function, right now I have to put it in each scope for it to work. 我试图找出如何在函数中重用变量,现在我必须将它放在每个范围内才能工作。

Say I have an jQuery Event handler: 假设我有一个jQuery事件处理程序:

$('.button').on('click', function() {
    var btn = $(this).data('button');
    $(this).addClass(btn+'-activate');
}).on('mouseup', function() {
     var btn = $(this).data('button');
     $(this).removeClass( btn+'-activate');
}).on('mouseleave', function() {
     var btn = $(this).data('button');
     $(this).removeClass( btn+'-activate');
}

How can I reuse the variable 'btn'? 如何重用变量'btn'? When I put it in the parent scope, it doesn't recognize $(this) anymore 当我把它放在父范围内时,它不再识别$(this)

The other answers have a bit of redundancy in them. 其他答案中有一些冗余。 Here is how I usually handle events that are related and have common variables: 以下是我通常处理相关事件并具有常见变量的方法:

$('.button').on('click mouseup mouseleave', function(event) {
    var btn = $(this).data('button');

    switch(event.type) {
        case 'click': {
            $(this).addClass(btn+'-activate');
            break;
        }

        case 'mouseup':
        case 'mouseout':
        case 'mouseleave': {
            $(this).removeClass(btn+'-activate');
            break;
        }
    }
});

Listen to multiple events and use a switch statement to determine which event was called. 侦听多个事件并使用switch语句来确定调用了哪个事件。

You can just iterate over the buttons, set the variable for each one and then use the variable inside the event handlers. 您可以迭代按钮,为每个按钮设置变量,然后在事件处理程序中使用变量。

$('.button').each(function() {
    var btn = $(this).data('button');
    $(this).on('click', function() {
        $(this).addClass(btn+'-activate');
    }).on('mouseup mouseleave', function() {
        $(this).removeClass( btn+'-activate');
    });
});

But of course this is not exactly the same as your code. 但是,这当然与您的代码完全不同。 Here we are setting the value of btn at the time the handlers are attached while, in the code of the question, btn is set at the time the handlers are called. 这里我们在处理程序附加时设置btn的值,而在问题的代码中,在调用处理程序时设置btn Therefore this is only a valid alternative if the value of .data('button') is not meant to change. 因此,如果.data('button')值不打算改变,这只是一个有效的替代方案。

There's no special advantage to using a variable. 使用变量没有特别的优势。 You can pass a function to .removeClass() and .addClass() thereby removing the need to use a variable: 您可以将函数传递给.removeClass().addClass()从而无需使用变量:

$(function() {
    $('.button').on('click', function() {
        $(this).addClass( function() {
            return $(this).data('button') + '-activate';
        });
    }).on('mouseup mouseleave', function() {
         $(this).removeClass( function() {
             return $(this).data('button') + '-activate';
         });
    });
});

  $(function() { $('.button').on('click', function() { $(this).addClass( function() { return $(this).data('button') + '-activate'; }); }).on('mouseup mouseleave', function() { $(this).removeClass( function() { return $(this).data('button') + '-activate'; }); }); }); 
 .one-activate { background-color:black; color:white; } .two-activate { background-color:black; color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button class="button" data-button="one">Man</button><br/> <button class="button" data-button="two">Woman</button><br/> 

BONUS : 奖金

As you can see the functions passed to .removeClass() and .addClass() are exactly identical. 正如您所看到的,传递给.removeClass().addClass()的函数完全相同。 We could write a jQuery custom method and use it in place of the functions as follows: 我们可以编写一个jQuery自定义方法并使用它代替函数,如下所示:

$(function() {
    $('.button').on('click', function() {
        $(this).addClass( $(this).btnActivate() );
    })
    .on('mouseup mouseleave', function() {
         $(this).removeClass( $(this).btnActivate() );
    });
});

$.fn.btnActivate = function() {
    return this.data('button') + '-activate';
};

  $(function() { $('.button').on('click', function() { $(this).addClass( $(this).btnActivate() ); }) .on('mouseup mouseleave', function() { $(this).removeClass( $(this).btnActivate() ); }); }); $.fn.btnActivate = function() { return this.data('button') + '-activate'; }; 
 .one-activate { background-color:black; color:white; } .two-activate { background-color:black; color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button class="button" data-button="one">Man</button><br/><br/> <button class="button" data-button="two">Woman</button><br/> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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