在循环访问jquery.each()时使用jquery.append()创建元素时遇到问题

时间:2010-10-28 04:26:25

标签: javascript jquery xhtml

当数据库中只有一个条目时,这很有用,但是添加另一个,现在我遇到了问题。因为我基于类名追加,所以我将每个元素附加到单个类中。我不知道该怎么做才能创建两个“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日星期三2010testtest博客| 2010年9月20日星期一这是来自 Joe Grigg

的第二篇博客文章     这是一个测试博客

测试博客| 2010年9月20日星期一

    这是一个测试博客

应该更像是:

第二次测试| 2010年10月27日星期三

这是来自 Joe Grigg

的第二篇博客文章

测试博客| 2010年9月20日星期一

这是一个测试博客。

感谢您的帮助。 -Joe

1 个答案:

答案 0 :(得分:1)

避免附加到您刚创建的内容:

$(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()不需要在每次迭代时定义。

相关问题