Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

javascript - dynamic update variables

let dpc;
let money;

if (getCookie("money") == -1) {
    money = 0;
} else {
    money = +getCookie("money");
    $("#money").html(money);
};

if (getCookie("dpc") == -1) {
    dpc = 1;
} else {
    dpc = +getCookie("dpc");
};

$(".dpc").click(function() {
    let thisCost = +$(this).find("span[id=dpcCost]").text();
    let thisBuff = +$(this).find("span[id=dpcBuff]").text();
    if (money < thisCost) {
        alert("not enough money")
    } else {
        dpc += thisBuff;
        money -= thisCost;
    };
});

let enemyNum = 0;
let currentEnemy = $(".enemy").eq(enemyNum);
let K = 100;
let health = currentEnemy.attr("data-health");
let k = K / health * dpc;
let MAX_HEALTH = health;

enemy.click(function(e) {
    if (currentHealth.html() != 0) {
        K -= k;
        health -= dpc;
        changeHealthBar();
        changeHealth();
        $(".minus-hp").remove();
        $(this).append(`<span class="minus-hp">-${dpc}</span>`)
        let posX = e.offsetX,
        posY = e.offsetY;
        $(".minus-hp").css({"top": posY,"left": posX});
    };
    if (currentHealth.html() == 0) {
        currentEnemy.addClass("defeat");
        setTimeout(removeOldEnemy, 1000);
    };
    if (currentHealth.html() < 0) {
        currentEnemy.addClass("defeat");
        setTimeout(removeOldEnemy, 1000);
        currentHealth.html(0);
    };
});

I have this code, the problem is that when I click on $(". dpc"), I change some variables, but in another place on click(enemy.click(function (e)), the original values of the variables are stored, how do I make it so that when I click on $(". dpc"), the variables change in enemy.click(function (e)?

question from:https://stackoverflow.com/questions/65853740/dynamic-update-variables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From what's is posted... The only variables changes on $(".dpc").click are dpc and money.

Now in the ennemy.click function, the only variable that may need to be updated is k.

So change K -= k; for K -= K / health * dpc;

And you possibly need to place it after health -= dpc;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...