开发者

how variable scope works in jquery?

var change = 1;

$("#game").click(function (e) {
    if (change == 1) {
        var data = $(e.target).closest("td").text();
        var p1 = $("#player1").val();
        var p1_value = p1 + data;
        $("#player1").val(p1_value);
        change = 2;
    } else(change == 2) {
        var data = $(e.target).closest("td").text();
        var p2 = $("#player2").val();
        var p2_value = p2 + data;
        $("#player2").val(p1_valu开发者_如何学Goe);
        change = 1;
    }

});

Is it the write way to write? BTW here it is not going to the else loop.


JavaScript has only function scope, not "curly bracket scope". If you want to be very correct, you would put all the declarations at the top of the function:

$("#game").click(function(e) {
    var data = '',
        p1 = '',
        p1_value = '',
        p2 = '',
        p2_value = '';

        if (change == 1) {
            data = $(e.target).closest("td").text();
            p1 = $("#player1").val();
            p1_value = p1 + data;
            $("#player1").val(p1_value);
            change = 2;
        }
        else if (change == 2) { // you forgot `if`
            data = $(e.target).closest("td").text();
            p2 = $("#player2").val();
            p2_value = p2 + data;
            $("#player2").val(p1_value);
            change = 1;
        }
});

At least JSLint complains about data being already defined.

But you can optimize (and shorten!) your function in another way:

$("#game").click(function(e) {
    var $player = $('#player' + change);
    $player.val($player.val() + $(e.target).closest("td").text());
    change = (change === 1) ? 2 : 1;
}


Your else should be an else if if you intend to use the condition:

if (change == 1) {
    // ...
} else if(change == 2) {
    // ...
}

As perhaps a better alternative, you can use jQuery's .toggle(), and pass it two functions which alternate on clicks.

$("#game").toggle(function(e) {
            var data = $(e.target).closest("td").text();
            var p1 = $("#player1").val();
            var p1_value = p1 + data;
            $("#player1").val(p1_value);
 }, function(e) {
            var data = $(e.target).closest("td").text();
            var p2 = $("#player2").val();
            var p2_value = p2 + data;
            $("#player2").val(p1_value);
 });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜