在html(heart var)之后追加计数var - jQuery

时间:2014-10-29 06:38:08

标签: javascript jquery

我的代码如下:

heart.html("<i class='glyphicon glyphicon-remove-sign'></i>&nbsp&nbsp&nbsp;"+count);

我想要heart.html()之外的count元素。类似的东西:

heart.html("<i class='glyphicon glyphicon-remove-sign'></i>&nbsp&nbsp&nbsp;")+count;

heart是一个可点击的div,我不希望计数可点击。

整个代码:

jQuery(document).ready(function()
{
    jQuery('body').on('click','.jm-post-like',function(event)
    {
        event.preventDefault();
        heart = jQuery(this);
        post_id = heart.data("post_id");
        heart.html("<i class='glyphicon glyphicon-cog'></i>");
        jQuery.ajax
        ({
            type: "post",
            url: ajax_var.url,
            data: "action=jm-post-like&nonce="+ajax_var.nonce+"&jm_post_like=&post_id="+post_id,
            success: function(count)
            {
                if( count.indexOf( "already" ) !== -1 )
                {
                    var lecount = count.replace("already","");
                    if (lecount === "0")
                    {
                        lecount = "0";
                    }
                    heart.prop('title', 'Like');
                    heart.removeClass("liked");
                    heart.html("<i class='glyphicon glyphicon-heart'></i>&nbsp&nbsp&nbsp;"+lecount);
                }
                else
                {
                    heart.prop('title', 'Unlike');
                    heart.addClass("liked");
                    heart.html("<i class='glyphicon glyphicon-remove-sign'></i>&nbsp&nbsp&nbsp;"+count);
                }
            }
        });
    });
});

function getPostLikeLink( $post_id )
{
   $like_count = get_post_meta( $post_id, "_post_like_count", true ); // Get post likes.
   $count = ( empty( $like_count ) || $like_count == "0" ) ? '0' : esc_attr( $like_count );
   if ( AlreadyLiked( $post_id ) )
   {
        $class = esc_attr( ' liked' );
        $title = esc_attr( 'Unlike' );
        $heart = '<i class="glyphicon glyphicon-remove-sign"></i>&nbsp&nbsp&nbsp;';
   }
   else
   {
        $class = esc_attr( '' );
        $title = esc_attr( 'Like' );
        $heart = '<i class="glyphicon glyphicon-heart"></i>&nbsp&nbsp&nbsp;';
   }
   $output = '<a href="#" class="jm-post-like'.$class.'" data-post_id="'.$post_id.'" title="'.$title.'">'.$heart.'&nbsp;</a>'.$count;
   return $output;
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您需要使用after()

heart.html("<i class='glyphicon glyphicon-remove-sign'></i>&nbsp&nbsp&nbsp;")
heart.after(count);

但是如果您多次调用脚本,则数字将保持预先设置而不是覆盖...所以

heart.html("<i class='glyphicon glyphicon-remove-sign'></i>&nbsp&nbsp&nbsp;");
var $counter = heart.next('.counter');
if (!$counter.length) {
    $counter = $('<span />', {
        'class': 'counter'
    }).insertAfter(heart);
}
$counter.html(count);