开发者

Trouble creating elements with jquery.append() while looping through jquery.each()

开发者 https://www.devze.com 2023-01-22 13:02 出处:网络
This worked great when there was only one entry in the database, but add another and now I\'ve got problems. Since I\'m appending based on class names I\'m getting every element appending to a single

This worked great when there was only one entry in the database, but add another and now I've got problems. Since I'm appending based on class names I'm getting every element appending to a single class. I don't know what to do in order to create two "blogHeadlines" with the appropriate content in each.

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('+')
            });
        });

The output of course is ridiculous, It looks kind of like this:

The second test | Wed Oct 27 2010test blog | Mon Sep 20 2010This is the second blog entry from Joe Grigg

This is a test blog

test blog | Mon Sep 20 2010

This is a test blog

It should be more like:

The second test | Wed Oct 27 2010

This is the second blog entry from Joe Grigg

test blog | Mon Sep 20 2010

This is a test blog.

Thanks for helping. -Joe


avoid to append to content you just created:

$(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:
   //...
});

And $('.toggleButton').live() does not need to be defined on every iteration.

0

精彩评论

暂无评论...
验证码 换一张
取 消