Reputation: 25
I am new to jQuery so this question might seem naive to you guys. But please help me out here.
I am creating a number of anchor tags dynamically with different titles and assigning different click event handler to those anchor tags that too dynamically.
All the anchor tags are getting created perfectly with different titles, but the problem is the event handler for them all is the same as the event handler for the last created anchor tag. So when I click any of the link they all go to the same page which is the page when you click the last link.
Here is the code
var title;
var node;
for(var i = 0; i < nodes.length; i++){
node = nodes[i];
title = node.getTitle();
jQuery("#displayNodeDetails")
.append(jQuery('<a></a>').attr({ href:'#' })
.html(title).click(function(){
EPCM.getSAPTop().LSAPI.AFPPlugin.service.navigate(node);
}));
}
Here "displayNodeDetails" is the division. I don't understand why all of my links have the same event handler when the value of the "node" is changing every time the loop runs and I can confirm because my code is creating four links: "User Admin", "System Admin", "Content Admin" and "Collaboration", but all the links are going to the same page as "collaboration".
Upvotes: 2
Views: 677
Reputation: 1964
Here's how I would rewrite your code to (hopefully) make it work:
// This is a quicker way of defining your loop.
for (node in nodes) {
// Setting the variable inside the loop so it doesn't pollute the global
// namespace unnecessarily.
var title = node.getTitle();
// Firstly build the link as a jQuery element
var link = jQuery('<a>' + title + '</a>').attr('href', '#');
// Then append it to the div
jQuery('#displayNodeDetails').append(link);
// Then set the click event callback on it inside a closure
link.click((function(node) {
return function() {
EPCM.getSAPTop().LSAPI.AFPPlugin.service.navigate(node);
};
})(node));
}
Upvotes: 1
Reputation: 10722
It is due to the fact that node
always points to the last node.
The click
handler gets called after the loop is done. So, the node
will point to the last element even in the handler functions of other anchors.
You need to pass the value of the current node
to the handler when creating it.
jQuery("#displayNodeDetails").append(jQuery('').attr({href:'#'}).html(title).click((function(node){
return function() { EPCM.getSAPTop().LSAPI.AFPPlugin.service.navigate(node); };
})(node));}
This way, the click
handler gets a function that has the correct node
passed to it by the function call.
Upvotes: 3