事件绑定 - 在闭包中捕获变量

时间:2014-06-19 12:25:23

标签: javascript jquery

我试图找出为什么它会警告“两个”我是否点击了“一个”或“两个”按钮。

<button id="one"> One </button>
<button id="two"> Two </button>

$(function(){
    var some_arg = 'one';
    $("#one").click(function(){
        my_alert(some_arg);
    });

    some_arg = 'two';

    $("#two").click(function(){
        my_alert(some_arg);
    });

});

function my_alert(test){
    alert(test);
}

谢谢!

Jsfiddle demo

4 个答案:

答案 0 :(得分:3)

因为你似乎想要使用一些闭包,所以也可以这样做:

$(function () {
    var some_arg = 'one';
    (function (some_arg) { // some_arg is local, no more referring to outter scoped one
        $("#one").click(function () {
            my_alert(some_arg); 
        });
    })(some_arg);

    some_arg = 'two';
    (function (some_arg) { // some_arg is local, no more referring to outter scoped one
        $("#two").click(function () {
            my_alert(some_arg);
        });
    })(some_arg);
});

--DEMO--

答案 1 :(得分:1)

点击事件在some_arg设置为&#39;两个&#39;

后触发
$(function(){
    var some_arg = 'one';
    $("#one").click(function(){
        my_alert(some_arg);
    });

    $("#two").click(function(){
        some_arg = 'two';
        my_alert(some_arg);
    });
});

答案 2 :(得分:1)

将您的代码更改为此DEMO

$(function(){

    var some_arg;//create a variable

    $("#one").click(function(){
        some_arg = 'one'; // assign 'one' to our variable  some_arg to 
        my_alert(some_arg);
    });



    $("#two").click(function(){
        some_arg = 'two';// assign 'two' to our variable  some_arg to 
        my_alert(some_arg);
    });

});

function my_alert(test){
    alert(test);
}

来源:Closures

答案 3 :(得分:0)

$(function(){
    var some_arg;
    $("#one").click(function(){
        some_arg = 'one';
        my_alert(some_arg);
    });

    $("#two").click(function(){
        some_arg = 'two';
        my_alert(some_arg);
    });

});