开发者

PHP foreach issue with jQuery

I have a foreach loop which loops and shows all the data in an array without a problem, however I have some jQuery I want applying to the results, but the jQuery only works on the first piece of data to be displayed. I am not really sure why, if anyone could help that would be great.

$count_limit = 0;
$limit = 5;

foreach ( $feeds->data as $item ) {
extract( (array) $item );
if($count_limit++  < $limit){
?>
<div id="news_post">
    <? $title_str = str_replace('–', '&#150;', $title) ?>
    <p class="news_title"><a href="<?php echo $link; ?>" target="_blank"><?php echo 开发者_JAVA技巧$title_str; ?></a> <a href="#" class="read">read...</a></p>
    <div class="news_desc"><?php echo "$description" ?></div>
</div>
<? }
else {
    break;
}


$(this).next('.news_desc').hide();
        $(this).next('a.read').click(function() {
            $(this).next('.news_desc').toggle();
        });


You forgot to post the jQuery you're using :-) But I suspect it's because all the divs you use have the same id ("news_post") so jQuery only uses the first id it finds.

You can postfix the id with $count_limit to make a truly unique id (HTML specs don't allow multiple elements with the same id attribute either) or change the way jQuery selects the elements to operate on (For example by classname).

EDIT: It's been a while since I used jQuery but this looks odd, why not just use:

$(.news_desc').hide();
$('a.read').click(function() {
  $(this).next('.news_desc').toggle();
});


So I would move the jQuery outside of the loop and I would hide each post by default with exception of the first.

$('.news_desc').not(':first').hide();

Then I would add a click even that will hide all except for the one selected.

$('a.read').click(function() {
     $('.news_desc').not(this).hide();
}

Not 100% sure this will work as it has been a while since I've used jQuery, but I assume you are looking to show only the post titles and have only 1 post description in view at a time.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜