我有一个 foreach 循环(使用 MVC3 的 Razor 引擎编写),并且我需要在每次迭代时在 Popups 数组中创建一个新对象。这是我正在尝试运行的内容:
var popups = [];
var count = 0;
@foreach (var marker in Model) {
<text>
popups[count]["content"] = document.createElement("div");
popups[count]["content"].class = "infobox-custom";
popups[count]["content"].style.cssText = "padding: 5px; width: 600px;";
popups[count]["content"].innerHTML = '<div class="professional"><h1>test</h1></div>';
popups[count]["infobox"] = new InfoBox();
popups[count]["marker"] = new MarkerInfo();
count++;
</text>
}
console.log(popups);
我收到错误:
Uncaught TypeError: Cannot set property 'content' of undefined
如您所见,我试图将每个单独标记的相关信息封装在一个 JavaScript 对象中。我的目标是使用 popups[index].marker
或 popups[index].content
等内容来访问我需要的所有内容。
我正在读《Javascript:The Good Parts》一书,其中有一个部分提到:
If the object does not already have that property name, the object is augmented:
我在这里缺少什么?
最佳答案
在开始向对象添加属性之前,将 popups[count]
设置为该对象。
var popups = [];
var count = 0;
@foreach (var marker in Model) {
<text>
popups[count] = {};
popups[count]["content"] = document.createElement("div");
popups[count]["content"].class = "infobox-custom";
popups[count]["content"].style.cssText = "padding: 5px; width: 600px;";
popups[count]["content"].innerHTML = '<div class="professional"><h1>test</h1></div>';
popups[count]["infobox"] = new InfoBox();
popups[count]["marker"] = new MarkerInfo();
count++;
</text>
}
console.log(popups);
关于javascript - 尝试向 javascript 对象添加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13557967/