Im stuck.
I have a button which returns information about a event, name, date and so on.
我有一个按钮,它返回有关事件,名称,日期等信息。
In the script it looks like this:
在脚本中它看起来像这样:
for(var i = 0; i < result.length ; i++)
{
var item = result[i];
$("#eventList").append("<h3>" + result.eventDate + "</h3>" + "<br>" + result.eventId + "<br>" + result.description + "<br>");
}
This generates a list of events that goes to a div, alla of the events in one div. But i would like every event to be placed in one separate div/box.
这将生成一个事件列表,这些事件将转到div,即一个div中事件的alla。但我希望每个事件都放在一个单独的div / box中。
Any ideas?
2 个解决方案
#1
You can create them inside a div and then append all of them at the end to the dom.
你可以在div中创建它们,然后将它们全部附加到dom的末尾。
var divs = [];
var $div;
results.forEach(function(item){
$div = $('<div></div>');
$div.append("<h3>" + item.eventDate + "</h3>");
$div.append("<br>"+ item.eventId);
$div.append("<br>"+ item.description);
divs.push($div);
});
$("#eventList").append(divs);
#2
You can create your item variable inside the for
loop. When ii
gets too big, result[ii]
will be undefined or false, and the loop will stop. I prefer to use ii
to i
, because it's easier to find if I want to search for a repeat loop.
您可以在for循环中创建项变量。当ii变得太大时,结果[ii]将是未定义或错误的,并且循环将停止。我更喜欢使用ii到i,因为如果我想搜索重复循环,则更容易找到。
Each jQuery operation returns the jQuery object that it was applied to, so you can chain your operations. You can create an empty element, and then set its text in the next operation, to make the code more compact.
每个jQuery操作都返回它应用的jQuery对象,因此您可以链接您的操作。您可以创建一个空元素,然后在下一个操作中设置其文本,以使代码更紧凑。
for(var ii=0, item; item=result[ii]; ii++) {
$("#eventList")
.append($("<div>")
.append($("<h3>").text(item.eventDate))
.append($("<p>").text(item.eventId))
.append($("<p>").text(item.description))
)
}
#1
You can create them inside a div and then append all of them at the end to the dom.
你可以在div中创建它们,然后将它们全部附加到dom的末尾。
var divs = [];
var $div;
results.forEach(function(item){
$div = $('<div></div>');
$div.append("<h3>" + item.eventDate + "</h3>");
$div.append("<br>"+ item.eventId);
$div.append("<br>"+ item.description);
divs.push($div);
});
$("#eventList").append(divs);
#2
You can create your item variable inside the for
loop. When ii
gets too big, result[ii]
will be undefined or false, and the loop will stop. I prefer to use ii
to i
, because it's easier to find if I want to search for a repeat loop.
您可以在for循环中创建项变量。当ii变得太大时,结果[ii]将是未定义或错误的,并且循环将停止。我更喜欢使用ii到i,因为如果我想搜索重复循环,则更容易找到。
Each jQuery operation returns the jQuery object that it was applied to, so you can chain your operations. You can create an empty element, and then set its text in the next operation, to make the code more compact.
每个jQuery操作都返回它应用的jQuery对象,因此您可以链接您的操作。您可以创建一个空元素,然后在下一个操作中设置其文本,以使代码更紧凑。
for(var ii=0, item; item=result[ii]; ii++) {
$("#eventList")
.append($("<div>")
.append($("<h3>").text(item.eventDate))
.append($("<p>").text(item.eventId))
.append($("<p>").text(item.description))
)
}