jQuery单击未正确追逐带有if条件的文本/数字


jquery click not chaning text/numbers correctly with if conditions

我正在用jquery写一个喜欢的按钮,但我在条件方面遇到了一些问题。

我遇到的另一个问题是total_likes计数器:如果我单击喜欢并单击不像计数器设置为 0,但如果我再次喜欢 te 计数器转到 2 而不是 1...

php/html:

if (total_likes > 0) {
    $hide = 'block';
} $hide = 'none';
$photos_box .= '<input type="hidden" class="tl' . $imgID . '" value="' . $total_likes . '" />
<a id="' . $imgID . '" class="like_button" title="' . $like_title . '">' . $like . '</a>
//the counter
<a id="" style="display: '. $hide . '">
    <span id="color" class="mod' . $imgID . '">' . $total_likes . '</span>
</a>
// the text
<li id="counter" style="display: ' . $hide . ';">
    <div id="">
        <span class="text_color">' . $text . '</span>
    </div>
</li>

jquery 脚本:

$('.like_button').click(function() {
    var total_likes = $('.tl'+this.id).val();
    total_likes = parseInt(total_likes);
    var status = '';
    if ($(this).html() == 'Like') {
        status = 'like';
        $(this).html('Unlike');
        $(this).attr('title', 'Unlike this');
        $('.mod'+this.id).html(total_likes+1);
        if (total_likes == 0) {
            $('#counter').slideToggle('fast');
            $('.text_color').html('Like this.');
        } else if (total_likes == 1) {
            $('.text_color').html('You and <a id="A_112">other</a> like this.');
        } else if (total_likes > 2) {
            var tl = total_likes+1;
            $('.text_color').html('You and <a id="A_112">'+tl+' others</a> like this.');
        }
    } else if ($(this).html() == 'Unlike') {
        status = 'unlike';
        $(this).html('Like');
        $(this).attr('title', 'Like this');
        $('.mod'+this.id).html(total_likes-1);
        if (total_likes == 0 || total_likes == 1) {
            $('#counter').slideToggle('fast');
        } else if (total_likes == 2) {
            $('.text_color').html('<a id="A_112">1 person</a> like this.');
        } else if (total_likes > 2) {
            var tl = total_likes-1;
            $('.text_color').html('<a id="A_112">'+tl+' people</a> like this.');
        }
    }
    var data = {
        img_id : this.id,
        sta    : status
    };
    $.ajax({
        type : 'POST',
        url  : '/includes/like.php',
        data : data
    }).done(function(result) {
        console.log(result);
    });
});

使用jquery和实时更改是一团糟...我不确定条件是否正确可以满足其需求。

我不知道为什么 like_counter-1 在做 -2,like_counter+1 在做 +2......

我做错了什么?

你不需要打印两次$total_likes...只需使用您的实际计数器:

var total_likes = $('.mod'+this.id).html();

老实说,您可能希望在工作时使用一些模板引擎,例如 Smarty 或其他一些引擎,因为它会导致混乱的代码 soner 或更高版本。

面临的问题是因为您没有将更新的值分配给隐藏字段。因此,最终您将替换一次值,但再次从未更新的字段中获取值

$('.tl'+this.id).val();

所以你可能想做这样的事情

total_likes = total_likes+1
$('.mod'+this.id).html(total_likes);
$('.tl'+this.id).val(total_likes);

希望这会有所帮助

快乐学习:)