Сохранение глобальной переменной в javascript в зависимости от того, какая кнопка была нажата


Я пытаюсь переключить мою игру на javascript на основе console.log()/prompt в визуальную игру для браузеров. Поэтому для этого я смешиваю jQuery с моим javascript.

1) я пытаюсь установить nHands = 1, 2, or 3, основываясь на том, какую кнопку нажимает пользователь. У меня есть 3 кнопки с одинаковым классом .smallbutton и уникальными классами .oneh .twoh и .threeh. 2) После того, как пользователь нажмет на любую из 3 кнопок, все кнопки исчезнут с помощью $('.smallbutton').detach();. Это прекрасно работает.

В Проблема с 1) выше. Он, кажется, не устанавливает nHands = ни к чему. Потому что для того, чтобы мой recordBetAmount(); запускал/делал что-то,он должен быть установлен равным 1,2 или 3. Почему nHands не устанавливается равным ничему?

Вот скрипка http://jsfiddle.net/cL9dx/ . Пожалуйста, обратите внимание, что скрипка включает в себя второй способ, который я пробовал.

Вот соответствующая часть моего кода:

var hand1, hand2, hand3, hD, nHands; //global vars

function numHands() {
    $('<p>Choose the number of hands you want to play.</p>').appendTo('.message');
    $('.oneh').click(function () {
        nHands = 1;
        $('.smallbutton').detach();
    });
    $('.twoh').click(function () {
        nHands = 2;
        $('.smallbutton').detach();
    });
    $('.threeh').click(function () {
        nHands = 3;
        $('.smallbutton').detach();
    });
    if (nHands > 0 && nHands < 4) {
        x = 150000 / nHands;
        if (nHands > 0) {
            hand1 = new Hand("First Hand", x, x, ".hand1");
            if (nHands > 1) {
                hand2 = new Hand("Second Hand", x, x, ".hand2");
                if (nHands > 2) {
                    hand3 = new Hand("Third Hand", x, x, ".hand3");
                }
            }
        }
    } else {
        $('<p>ERROR!!!</p>').appendTo('.message');
    }
}

....
numHands();
recordBetAmount();

edit: я даже пытался сделать вышеупомянутую функцию numHands в два отдельные функции, но по-прежнему не похоже, чтобы nHands = ни к чему.

3 3

3 ответа:

Попробуйте разделить логику функции numHands на две функции. Первый прикрепит обработчики событий к вашим кнопкам, а остальные сделают расчет следующим кодом здесь. И вложите свой код внутрь $(document).готовый();. И в соответствии с примером jsFiddle вы передаете параметр nHands в функцию, поэтому удалите глобальную дикларацию nHands. здесь - это jsfiddle, который работает. Другое дело, если Вы читаете о глобальной переменной nHands, другие ваши функции, такие как recordBetAmount и так далее. должно быть изменено соответствующим образом. Потому что они не признают, что переменная nHands объявлена. И это дает Uncaught ReferenceError: nHands is not defined в консольном выводе. функция recordBetAmount должна быть изменена. Вы вызываете его, когда документ готов. Однако мне кажется, что эта функция должна быть вызвана после того, как люди делают ставку.

$(document).ready(function()
{    
suits = ["s", "d", "c", "h"];
deck = [];
var hand1, hand2, hand3, hD; //global vars

   ...

function numHands() {
    var nHands;
    $('<p>Choose the number of hands you want to play.</p>').appendTo('.message');
        $('.oneh').click(function() {
            nHands = 1;
            $('.smallbutton').detach();
            numhands2(nHands); });
        $('.twoh').click(function() {
            nHands = 2;
            $('.smallbutton').detach();
            numhands2(nHands); });
        $('.threeh').click(function() {
            nHands = 3;
            $('.smallbutton').detach();
            numhands2(nHands); });

function numhands2(nHands) {
    console.log(nHands);
    if (nHands > 0 && nHands < 4) {
        x = 150000/nHands;
        if (nHands > 0) { hand1 = new Hand("First Hand", x, x, ".hand1");
            if (nHands > 1) { hand2 = new Hand("Second Hand", x, x, ".hand2");
                if (nHands > 2) { hand3 = new Hand("Third Hand", x, x, ".hand3"); } }
        hD = new Hand("Dealer", 4500200 , 4500200 , ".handD"); } }
    else { $('<p>ERRRORRRRR</p>').appendTo('.message'); } }
}

....

});

Или функции marge numHands2 и recordBetAmount.

function numhands2(nHands) {
    console.log(nHands);
    if (nHands > 0 && nHands < 4) {
        x = 150000/nHands;
        if (nHands > 0) { hand1 = new Hand("First Hand", x, x, ".hand1");
            if (nHands > 1) { hand2 = new Hand("Second Hand", x, x, ".hand2");
                if (nHands > 2) { hand3 = new Hand("Third Hand", x, x, ".hand3"); } }
        hD = new Hand("Dealer", 4500200 , 4500200 , ".handD"); } }
    else { $('<p>ERRRORRRRR</p>').appendTo('.message'); } }
}

function recordBetAmount() {
    if (nHands > 0) { setBetAmount(hand1);
        if (nHands > 1) { setBetAmount(hand2);
            if (nHands > 2) { setBetAmount(hand3); } } } }

Я пытался делать то, что вы хотите, просто некоторые изменились:

$(document).ready(function () {
    var Hand = function Hand() {
        //your Hand class
    };

    var NumHands = function NumHands(callback) {
        var $this = this;
        this.callback = callback;
        this.hand1 = null;
        this.hand2 = null;
        this.hand3 = null;
        this.hD = null;
        this.nHands = null;

        $('<p>Choose the number of hands you want to play.</p>').appendTo('.message');
        $('.oneh').click(function () {
            $this.detachAndCreate(1);
        });
        $('.twoh').click(function () {
            $this.detachAndCreate(2);
        });
        $('.threeh').click(function () {
            $this.detachAndCreate(3);
        });
        this.detachAndCreate = function (val) {
            this.nHands = val;
            $('.smallbutton').detach();
            this.createHands();
            if (jQuery.isFunction(this.callback)) this.callback.call(this);
        };
        this.createHands = function () {
            if (this.nHands > 0 && this.nHands < 4) {
                var x = 150000 / this.nHands;
                if (this.nHands > 0) {
                    this.hand1 = new Hand("First Hand", x, x, ".hand1");
                    if (this.nHands > 1) {
                        this.hand2 = new Hand("Second Hand", x, x, ".hand2");
                        if (this.nHands > 2) {
                            this.hand3 = new Hand("Third Hand", x, x, ".hand3");
                        }
                    }
                }
            } else {
                $('<p>ERROR!!!</p>').appendTo('.message');
            }
        };
    };

    function recordBetAmount () {
        //here 'this' refers to numHands instance
    };

    var numHands = new NumHands(recordBetAmount);
});

Обновить

Обновите свой jsfiddle и удалите код, не необходимый для этой проблемы, и добавьте комментарии, чтобы объяснить изменения

Http://jsfiddle.net/raunakkathuria/cL9dx/4/


Проблема в соответствии с вашим кодом заключается в том, что вы вызываете numHands() и recordBetAmount() оба при загрузке документа, но nHands устанавливается, когда пользователь нажимает на любую кнопку, поэтому вы можете сделать так

var hand1, hand2, hand3, hD, nHands; //global vars

function recordBetAmount() {
  alert("Finally nHands is " + nHands);
}

$(document).ready(function () {
       $('.oneh').click(function() {
            nHands = 1;
            alert("First " + nHands);
            $('.smallbutton').detach(); 
            numHands();
        });
        $('.twoh').click(function() {
            nHands = 2;
            alert("Second " + nHands);
            $('.smallbutton').detach(); 
            numHands();
        });
        $('.threeh').click(function() {
            nHands = 3;
            alert("Third " + nHands);
            $('.smallbutton').detach(); 
            numHands();
        });
});

function numHands() {
    $('<p>Choose the number of hands you want to play.</p>').appendTo('.message');

    recordBetAmount();
    if (nHands > 0 && nHands < 4) {
        x = 150000/nHands;
        if (nHands > 0) { hand1 = new Hand("First Hand", x, x, ".hand1");
            if (nHands > 1) { hand2 = new Hand("Second Hand", x, x, ".hand2");
                if (nHands > 2) { hand3 = new Hand("Third Hand", x, x, ".hand3");
        } } } }
    else { 
        $('<p>ERROR!!!</p>').appendTo('.message'); 
    }


}

Проверка http://jsfiddle.net/raunakkathuria/NWQ8j/1/