[英]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.