gpt4 book ai didi

javascript - 带有匿名方法问题的 Jquery .click()

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:14:47 25 4
gpt4 key购买 nike

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

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 的新手,所以我不明白为什么第一次尝试有效而不是后者

最佳答案

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

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) { ...
}

关于javascript - 带有匿名方法问题的 Jquery .click(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34482856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com