简体   繁体   English

从全局范围删除var

[英]remove var from global scope

In this example I have two action : 在此示例中,我有两个操作:

  1. when you add quantity of users - it will be automatically calculated by a price in the input with total sum 当您添加用户数量时-它将自动由输入中的价格加上总金额来计算

  2. when you already add the quantity of users > total sum is calculated > if you click on EUR - in input with total sum, the sum will be translated to euro. 如果您已经添加了用户数量>已计算总金额>如果单击EUR-输入总金额,则总金额将转换为欧元。

So, every thing work fine - but I don't like that the "usesQuantity" has the global scope! 因此,一切正常-但我不喜欢“ usesQuantity”具有全局范围! Any ideas how make it local and save the working version http://jsfiddle.net/gb2447jd/5/ 任何想法如何使其本地化并保存工作版本http://jsfiddle.net/gb2447jd/5/

tried something like: 尝试过类似的东西:

$('#user-quantity').keyup(function(){
    var userQuantity = parseInt($(this).val());
    if( userQuantity >=1 && userQuantity <=200){
      valid(userQuantity);
    } else {
      $('#total-sum').val("error");
    }
  });


  $('#usd').on('click', function(){
    $('#eur').removeClass('greenChacked');
    $(this).addClass('greenChacked');
    valid(userQuantity);
  });
  $('#eur').on('click', function(){
    $('#usd').removeClass('greenChacked');
    $(this).addClass('greenChacked');
    valid(userQuantity);
  });
  $('#usd').trigger('click');

  function valid(userQuantity){
    if( $('#usd').hasClass('greenChacked') ){
      var usdCurr = userQuantity * 10 + 'doll';
      $('#total-sum').val(usdCurr);
    }
    if( $('#eur').hasClass('greenChacked') ){
      var eurCurr = userQuantity * 5 + 'eur';
      $('#total-sum').val(eurCurr);
    }
  }

Define your variable (userQuantity) within the function. 在函数内定义变量(userQuantity)。 It will be available via closure to the other functions and callbacks without having global scope. 无需全局作用域,就可以通过关闭其他函数和回调来使用它。 See this new jsFiddle . 看到这个新的jsFiddle

The start of the new code looks as follows: 新代码的开头如下所示:

$(document).ready(function () {
    var userQuantity;
    $('#user-quantity').keyup(function () {
        userQuantity = parseInt($(this).val());
        if (userQuantity >= 1 && userQuantity <= 200) {
            setCurrency();
        } else {
            $('#total-sum').val("error");
        }
    });

You could wrap your code inside a immediately invoked function 您可以将代码包装在立即调用的函数中

(function () {
    var userQuantity;

    $(document).ready(function () {
        //rest of your code 
    };
}());

More info here . 更多信息在这里

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

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