1

Hi i have a very specific problem which i cant find a solution for: im creating list items in an unordered list in the html-file and trying to add an onmousedown-function which should pass a mouseevent and the id of the field as parameter

for (var i=0;i<10;i++){
$('ul').append('<li id='+i+'>text</li>');
$(i).on('mousedown', function(event){ Callfunction(i,event);});
}

Callfunction(i, event){
alert(i,' ',event);
}

unfortunately only the maximal iterator(i=9) gets passed by each function i think this has to do with how .on() works. does a workaround exist? maybe by forcing parameter i in Callfunction(i,event); to be the actual string?

I need the function to be implemented via .on() or .bind() because have to be able to remove the click-functionality later. please try to keep it simple, im still a beginner. thanks edit: typo

4

1 回答 1

1

范围问题,您可以使用闭包:

for (var i = 0; i < 10; i++) {
    $('ul').append('<li id="' + i + '">text</li>');
    (function (i) {
        $('#' + i).on('mousedown', function (event) {
            Callfunction(i, event);
        });
    })(i);
}

function Callfunction(i, event) {
    alert(i, ' ', event); // better is to use console.log() instead of alert()
}
于 2013-07-16T11:39:29.660 回答