将函数应用于每个div

时间:2013-02-02 09:34:45

标签: javascript jquery html ajax

所以基本上我有n个持有注释的div,就像在facebook上一样,在Jquery中我有一个运行ajax调用的函数来获取每个div的注释,至少这是我想要它做的,它只是获取页面上第一个div的注释,如何同时为每个div运行该函数?

以下是代码:Ajax

interval = setInterval(function(){
    comment_id = $("#main-photo"+k).attr("commentid");
    k = $("#main-photo"+k).attr("nr_crt");
    $.post('../utility/countcomm.php', { comment_id: comment_id } , 
        function(output) {
            if (+total1 < +output)
                total1 = output;
            if (+total1 > +total2)
            {   
            $.post('../utility/fetchcomments.php', { comment_id: comment_id, start:total2, end:total1 } , 
                function(output1) {
                    $(".comment_append"+k).append("<p class='comment'>"+output1+"</p>");
                    var scrolldown = $('.comment_append'+k)[0].scrollHeight;
                    $('.comment_append'+k).animate({scrollTop:scrolldown}, 200);
                });
            total2 = total1;
            }
        });
},100);

HTML:

<div id="comment_box">
    <input type="text" name="comment" id="type_comment" value="Type a comment." />
    <div id="comment_append" class="comment_append<?php echo $k; ?>">

    </div><!--comment_append end-->
    <img id="main-photo<?php echo $k; ?>" nr_crt="<?php echo $k; ?>" class="main-photo" src="<?php echo $user_uploads['pic1'] ?>" width="<?php echo $width; ?>"  height="<?php echo $height; ?>" commentid="<?php echo $user_uploads['comment_id']; ?>"/>
</div><!--comment_box end-->

每个div在php中动态分配不同的id。 谢谢。

1 个答案:

答案 0 :(得分:1)

当我正确阅读/理解您的代码时,您想要使用类主照片查找所有图像,获取荣誉并更新相关的div?在这种情况下,您需要在该类的所有图像上循环:

interval = setInterval(function(){
    // loop over all images with the class
    $(".main-photo").each( function() {
        // get the comment_id and k (the unique part of the id)
        var $element = $(this),
            comment_id = $element.attr("commentid"),
            k =  $element.attr("nr_crt");
        // the rest is unchanged...
        $.post('../utility/countcomm.php', { comment_id: comment_id } , 
        function(output) {
            if (+total1 < +output)
                total1 = output;
            if (+total1 > +total2)
            {   
            $.post('../utility/fetchcomments.php', { comment_id: comment_id, start:total2, end:total1 } , 
                function(output1) {
                    $(".comment_append"+k).append("<p class='comment'>"+output1+"</p>");
                    var scrolldown = $('.comment_append'+k)[0].scrollHeight;
                    $('.comment_append'+k).animate({scrollTop:scrolldown}, 200);
                });
            total2 = total1;
            }
        });

    });
},100);

顺便说一句,你应该考虑定期刷新设置(100毫秒)会产生大量的服务器请求。根据数据量的不同,可能会出现一些问题。