![](/img/trans.png)
[英]Pushing/Creating elements dynamically in jQuery and then immediately looping through to append HTML
[英]Trouble creating elements with jquery.append() while looping through jquery.each()
当数据库中只有一个条目时,这很好用,但是添加另一个条目,现在我遇到了问题。 由于我基于类名进行追加,因此我将每个元素追加到单个类中。 我不知道如何创建两个各自具有适当内容的“ blogHeadlines”。
jQuery的:
$(blogEntries).each(function () {
//Create the blog headline element
$('#blogPage').append($('<div class="blogHeadline">'));
//Add the toggle button
$('.blogHeadline').append('<input class="toggleButton" type="button" value="+" />');
//Append the title and the date to the blogHeadline
$('.blogHeadline').append('<span class="blogTitle">' + this.Title + ' | </span>');
//Cast the date to a Date object
var BlogDate = new Date(this.Date);
$('.blogHeadline').append('<span class="blogDate">' + BlogDate.toDateString() + '</span>');
//Add the blog content element
$('#blogPage').append($('<div class="blogContent">'));
//Append the blog entry
$('.blogContent').append(this.Entry);
//Toggle the blog content
$('.toggleButton').live("click", function () {
$('.blogContent').slideToggle('slow');
$('.toggleButton').val() == "+" ? $('.toggleButton').val('-') : $('.toggleButton').val('+')
});
});
输出当然是荒谬的,看起来像这样:
第二次测试 2010年10月27日星期三测试博客| 2010年9月20日星期一这是乔·格里格 ( Joe Grigg )的第二篇博客文章这是一个测试博客
测试博客| 2010年9月20日星期一这是一个测试博客
应该更像是:
第二次测试 2010年10月27日,星期三
这是乔·格里格的第二篇博客文章
测试博客| 2010年9月20日星期一
这是一个测试博客。
感谢您的帮助。 -乔
避免附加到您刚刚创建的内容:
$(blogEntries).each(function () {
//Create the blog headline element
var BlogDate = new Date(this.Date);
var Headline = $('<div class="blogHeadline" />');
Headline.append('<input class="toggleButton" type="button" value="+" />')
.append('<span class="blogTitle">' + this.Title + ' | </span>')
.append('<span class="blogDate">' + BlogDate.toDateString() + '</span>')
.appendTo('#blogPage');
// now do something similar with your Content:
//...
});
$('。toggleButton')。live()不需要在每次迭代中都定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.