简体   繁体   English

Ajax投票系统投票显示

[英]Ajax voting system vote display

I'm using a ajax voting system in one of my projects. 我在其中一个项目中使用ajax投票系统。 Problem is I'm using a div with a id to display the votes. 问题是我正在使用具有ID的div显示投票。 So when ever someone click vote up or down in any of the posts (there are so many posts in one page. it is a php loop) it always end up displaying in the 1st div. 因此,无论何时有人在任何帖子中单击上下投票(一页中有很多帖子。这是一个php循环),它总是最终显示在第一个div中。 This is my code 这是我的代码

$(function() {
    $(".vote").click(function() {
        var id = $(this).attr("id");
        var name = $(this).attr("name");
        var dataString = 'id=' + id;
        var parent = $(this);
        if (name == 'up') {
            $(this).fadeIn(200).html;
            $.ajax({
                type: "POST",
                url: "vote_up.php",
                data: dataString,
                cache: false,
                success: function(html) {
                    $("#display-vote").html(html);
                }
            });
        } else {
            $(this).fadeIn(200).html;
            $.ajax({
                type: "POST",
                url: "vote_down.php",
                data: dataString,
                cache: false,
                success: function(html) {
                    $("#display-vote").html(html);
                }
            });
        }
        return false;
    });
});

HTML 的HTML

<div class="vote-box">

<a href="" class="vote" id="<?php echo $PostId; ?>" name="up"></a>

<div id="display-vote"><?php echo $Votes; ?></div>

<a href="" class="answer-vote down" id="<?php echo $PostId; ?>" name="down"></a>

</div>

Is there is anyway that i can display votes in the correct place? 无论如何,我可以在正确的位置显示投票吗? Really appropriate any help. 真的很合适任何帮助。

Surely just don't use an ID? 当然只是不使用ID?

HTML: HTML:

<div class="vote-box">

   <a href="" class="vote" id="<?php echo $PostId; ?>" name="up"></a>

   <div class="display-vote"><?php echo $Votes; ?></div>

   <a href="" class="answer-vote down" id="<?php echo $PostId; ?>" name="down"></a>

</div>

JavaScript: JavaScript:

success: function(html) {
    $(this).parent().find('.display-vote').html(html);
}

Id attribute should be unique . id属性应该是唯一的 if you have multiple elements with same id, when doing something like this $('#myNotSoUniqueId') will always return you first one. 如果您有多个具有相同ID的元素,则在执行类似$('#myNotSoUniqueId')时,始终会返回第一个。

As a quick solution I would recommend instead of 作为一种快速解决方案,我建议您选择

<div id="display-vote"><?php echo $Votes; ?></div>

have something like 有类似的东西

<div class="display-vote" data-id="<?php echo $PostId; ?>">
  <?php echo $Votes; ?>
</div>

and in javascript to have something like this: 并在javascript中具有以下内容:

$(".display-vote[data-id='" + postId +"'])

to select element by specific data-id attribute 通过特定的data-id属性选择元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM