我正在尝试创建动态弹出窗口内容它工作正常,问题是它显示所有弹出窗口的一个HTML内容。请帮我找出解决方案
下面给出了我的代码,下面给出了我的示例日期
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;
答案 0 :(得分:1)
你的问题是divDetails
被保存在一个闭包中,所以每次调用content函数时,它都返回相同的divDetails
对象(在最后一次循环运行时创建的对象) )。
最简单的解决方案是简单地设置没有功能的内容:
$(img).popover({
html : true,
content : divDetails
});
另一种解决方案是为每次调用popover创建一个新范围:
(function(div) {
$(img).popover({
html : true,
content : function() {
return div;
}
});
})(divDetails);