Can someone tell me what I am doing wrong here? I simplified it below but I am basically trying to create a list and have a click event that references a variable only available in the loop.
for (var i = 0; i < data.length; i++) {
$newRow = $(rowFormat);
$('a:first', $newRow).click(function(i){
return function() { alert(i); }
});
$list.append($newRow);
}
You aren't calling the outer function.
$('a:first', $newRow).click(function(j){
return function() { alert(j); }
}(i)); /* Pay special attention to this line, it is where the major change is */
As TJ Crowder mentioned, you can move the factory out of the loop.
function my_factory(j) {
return function() {
alert(j);
};
}
$('a:first', $newRow).click(my_factory(i));
You've almost got it, just one small change. This is actually my favorite example of a practical use of a closure in Javascript.
Basically, you need to create a function that takes a value, and returns a function that uses that value. See the commented line below for what your example is missing. Your code created the anonymous function, but didn't invoke it.
for (var i = 0; i < data.length; i++) {
$newRow = $(rowFormat);
var fn = (function (value) {
return function() {
alert(value);
};
}) (i); //this is what you were missing, you need to invoke the anonymous function
$('a:first', $newRow).click(fn);
$list.append($newRow);
}
Use 'bind' to attach the 'click' event and pass a parameter. Using 'event.data' you will be able to get the right value of your parameter:
Example 1:
$(document).ready(function()
{
for (var i = 0; i < data.length; i++)
{
$newRow = $(rowFormat);
$('a:first', $newRow).bind('click', {i: i},
function (event)
{
alert(event.data.i);
}
);
$list.append($newRow);
}
});
Example 2:
$(document).ready(function()
{
$(".selectorA").each(function()
{
var elementId = $(this).attr("id");
for(var i = 0; i < 20; i++)
{
$('#question' + i).bind('click', {currentIndex: i, elementId: elementId},
function (event)
{
alert(event.data.currentIndex + " | " + event.data.elementId);
}
);
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.