javascript – 带有unanonymus方法问题的Jquery .click()

我正在关注和修改教程,希望创建一个交互式技能树表

var main = function() {
    var points = parseInt($('.resume').text());
    var pointExpended = 0; 


    $('.node').click(function() {
        var cost = parseInt($(this).children('.info').children('.cost').text());
        if($(this).hasClass('active-node')) {
            //l'abilità viene rimossa 
            $(this).removeClass('active-node');
            pointExpended = pointExpended - cost;
            $('.resume').text(points-pointExpended);
        }
        else {
            //l'abilità viene comprata
            if(points-(pointExpended+cost) < 0) {
                alert("Limite dei punti superato");
            }
            else {
            $(this).addClass('active-node');
            pointExpended = pointExpended + cost;
            $('.resume').text(points-pointExpended);
            }
        }
    });
   };


   $(document).ready(main);

添加一些递归我试图将处理程序放入外部函数

var click_handler = function() {

        alert(points);

        var cost = parseInt($(this).children('.info').children('.cost').text());
        if($(this).hasClass('active-node')) {
            //l'abilità viene rimossa 
            $(this).removeClass('active-node');
            pointExpended = pointExpended - cost;
            $('.resume').text(points-pointExpended);
        }
        else {
            //l'abilità viene comprata
            if(points-(pointExpended+cost) < 0) {
                alert("Limite dei punti superato");
            }
            else {
            $(this).addClass('active-node');
            pointExpended = pointExpended + cost;
            $('.resume').text(points-pointExpended);
            }
        }
    }

var main = function() {
    var points = parseInt($('.resume').text());
    var pointExpended = 0; 

    alert(points);

    $('.node').click(click_handler);
};


$(document).ready(main); 

但代码不响应点击.

我对jscript / jquery很新,所以我无法理解为什么第一次尝试有效而不是后者

最佳答案 变量点和pointEtended对你的点击处理程序是不可见的(变量范围是一个词法的东西,并且在调用堆栈上不起作用..)所以你需要用一个闭包传递它们:

var main = function() {
    var points = parseInt($('.resume').text());
    var pointExpended = 0; 

    alert(points);

    $('.node').click(function(evt) {
              click_handler(evt, points, pointExtended)
    });
};

还修改click_handler以接受命名值

click_handler(evt, points, pointExtend) { ...
}
点赞