I am trying to create dynamic popover content It worked fine, the problem is it shows one html content for all the popover. Please help me to find out the solution
My code is given below and also my example date is given below
var div = $("<div>").addClass("pull-right vitalDeviceConnectedIcon");
var vitals = ["Steps", "floor"];
var device = [{
"apiId": "1",
"accountDeviceId": "83",
"manufacturerId": "26",
"device": "Fitbit One",
"api": "/fitbit/updatefitbitdata"
}, {
"apiId": "2",
"accountDeviceId": "91",
"manufacturerId": "32",
"device": "Up",
"api": "/oauth/jawboneupdate"
}, {
"apiId": "4",
"accountDeviceId": "92",
"manufacturerId": "34",
"device": "BG5",
"api": "/oauth/ihealthupdate"
}];
for (var i = 0; i < device.length; ++i) {
var img = $("<img>");
if (device[i].apiId == "1") {
$(img).attr("src", "img/fitbit_iconsm.png");
}
if (device[i].apiId == "2") {
$(img).attr("src", "img/jawbone_iconsm.png");
}
if (device[i].apiId == "4") {
$(img).attr("src", "img/ihealth_iconsm.png");
}
$(img).data("data", device[i]);
$(img).click(function() {
var deviceInfo = $(this).data("data");
syncDevices(deviceInfo.api, deviceInfo.accountDeviceId, vitalId, vitalName, deviceInfo.device);
});
var divDetails = $("<div>");
var label = $("<label>").html("Device: " + device[i].device);
var ul = $("<ul>")
$(divDetails).append(label);
$(divDetails).append(ul);
for (var j = 0; j < vitals.length; ++j) {
var li = $("<li>").html(vitals[j]);
$(ul).append(li);
}
var pForText = $("<p>").html("Please click on the icon to update the vital values");
$(divDetails).append(pForText);
$(img).attr("data-toggle", "popover");
$(img).attr("data-placement", "top");
$(img).attr("data-trigger", "hover");
console.info($(divDetails).html());
try {
$(img).popover("destroy");
} catch(err) {
}
$(div).append(img);
$(img).popover({
html : true,
content : function() {
return divDetails;
},
});
}
return div;
Your problem is that divDetails
is saved in a closure, and so every time the content function is called, it returns the same divDetails
object (the one that's created on the last run of the loop).
The easiest solution is simply setting the content without a function:
$(img).popover({
html : true,
content : divDetails
});
Another solution is to create a new scope for each call to popover:
(function(div) {
$(img).popover({
html : true,
content : function() {
return div;
}
});
})(divDetails);