【问题标题】:Interchange buttons to JS by deactivating and reactivating them通过停用和重新激活按钮与 JS 交换按钮
【发布时间】:2020-05-22 08:26:14
【问题描述】:

所以我们开始吧,我有 2 个按钮可以在它们之间切换,我想确保在再次绑定之前删除点击以避免垃圾邮件。按钮会一直切换,除非在 playRound 点击我们得到一个 JSON 告诉我们否则。

我希望在他点击之后,在我再次将按钮与下一个按钮绑定之前,它无法再次执行此操作。

这就是我尝试过的:

“NextStage”按钮绑定函数

function bindNextStage() {
    $('#nextStage').show().click(function () {
        let $pkEnemy = document.getElementById('pkEnemy').innerText;
        $('#nextStage').hide().click(false);
        $.ajax({
            url: '/nextEnemy/' + $pkEnemy,
            type: 'get',
            dataType: 'json',
        }).done(function (result) {
            console.log("refresh some data");
            bindPlayRound();
        });
    });
}

绑定playRound的函数

function bindPlayRound($pkParty) {
    $('#playRound').show().click(function () {
        let $pkEnemy = document.getElementById('pkEnemy').innerText;
        $('#playRound').click(false).hide();
        $.ajax({
            url: '/playRound/' + $pkEnemy,
            type: 'get',
            dataType: 'json',
        }).done(function (result) {
                addBattleReport(result).then(r => {
                    console.log("do something with an other button")
                });
                console.log("refresh some data")
                if (result['isEnded'])
                        console.log('END');
                else if (result['enemy']['hp'] <= 0) {
                    bindNextStage();
                }
                else{
                    bindPlayRound()
                }
        });
    });
}

我要求开始

bindNextStage()

----编辑----

目前,如果我按 F12 并显示该按钮,我可以再次单击该按钮,但除此之外,该功能还会启动 3 次。当我单击该按钮时,它隐藏得很好,但它没有解除绑定,并且在启动 3 次时有一个奇怪的行为。

----编辑2---

我知道“.click”函数不会被 .click(false) 解除绑定这一事实会像绑定它一样多次启动我的函数。

【问题讨论】:

  • 你能更详细地写出你所面临的错误吗?以便人们了解问题
  • 目前,如果我执行 F12 并显示该按钮,我可以再次单击该按钮,但除此之外,该功能还会启动 3 次。当我点击该按钮时,它隐藏得很好,但它没有解除绑定,并且在启动 3 次时有一个奇怪的行为。
  • 感谢您的补充。在下面检查我的答案。

标签: javascript json button binding


【解决方案1】:

您可以使用jQuery 的off()unbind() 函数来移除按钮上的事件监听器。它会起作用,而不是你使用click(false)

 $('#nextStage').hide().unbind("click");
 $('#playRound').hide().unbind("click");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-01
    • 2012-02-04
    • 2019-04-06
    • 2013-03-05
    • 1970-01-01
    • 2020-09-10
    • 2011-05-01
    • 2023-02-13
    相关资源
    最近更新 更多