Reputation: 421
Consider the following code...
function getItems(id, menu_id) {
//some code
}
$('#group-api').append('<li><a href="#" onclick="getItems(\''+data['group'][i]['id']+'\',\''+menu_id+'\');" role="tab" data-toggle="tab">'+data['group'][i]['menu_group']+'</a></li>');
This works if I use Chrome, but not for Firefox. Any solutions? Thanks.
Upvotes: 0
Views: 251
Reputation: 2780
Try the opposite way. Create the element via jQuery, append a .click()
event on it, and then append it to the containter.
Code:
function getItems(id, menu_id) {
// ...
}
$("<li><a href='#' role='tab' data-toggle='tab'>" + data['group'][i]['menu_group'] + "</a></li>")
.appendTo("#group-api")
.find("a")
.click(function() {
getItems(data['group'][i]['id'], menu_id);
});
JSbin mock-up: http://jsbin.com/dosohatawe/1/edit?js,console,output
Reply to comment:
You always get the last value because you did not use a closure. Here is your (non-working) example updated with the use of closures:
for(var i = 0; i < data['group'].length; i++) {
var id = data['group'][i]['id'];
$("<li><a href='#' role='tab' data-toggle='tab'>" + data['group'][i]['menu_group'] + "</a></li>")
.appendTo("#group-api")
.find("a")
.click(
(function(a, b) {
return function() {
getItems(a, b);
};
})(id, menu_id)
);
}
I haven't tested it, but I think it should work.
Upvotes: 3