开发者

How to pass a 'constant' parameter in jquery

开发者 https://www.devze.com 2023-04-01 08:50 出处:网络
I have the following attached to a div element, which detects when a user right clicks on a div and calls the function theFunction.

I have the following attached to a div element, which detects when a user right clicks on a div and calls the function theFunction.

$('#box_'+i).bind('mousedown',function(e){if(e.which==3)theFunction(e,i)});

The code is run inside a loop (where the i variable that is incremented), as there are multiple divs that need right click functionality on the page. However开发者_Go百科 when theFunction is called it always passes the last value of i instead of the value that it was when the bind() was done. Is there a way to make it constant so it wont change i for the previous divs as the loop is run?


You'll have to capture the value of i in a local scope, inside of your loop:

// Start your loop
(function(i){
    $('#box_'+i).bind('mousedown', function(e){
        if (e.which==3) theFunction(e,i)
    });
})(i);
// end your loop


The closure solutions are all good (they work just fine), but I thought I'd point out another way to do it. You can also access the object that triggered the event and pull the number off the id of the object. That would work something like this:

$('#box_'+i).bind('mousedown',function(e){
    var matches = this.id.match(/_(\d+)$/);
    var num = parseInt(matches[1], 10);
    if(e.which == 3) theFunction(e, num);
});

Or if you really want to be object oriented (and use a neat capability of jQuery), you can save the index value as a separate data item associated with the object and retrieve it from there later.

$('#box_'+i).data("index", i).bind('mousedown',function(e){
    if(e.which == 3) theFunction(e, $(this).data("index"));
});

Working demo of the second method here: http://jsfiddle.net/jfriend00/wVDHw/


for(var i=0;i<100;i++)
    (function(i){
        $('#box_'+i).bind('mousedown',function(e){
            if(e.which==3)
                theFunction(e,i);
         });
    })(i);
0

精彩评论

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