Pass response of AJAX only to current div among an array

前端 未结 2 1488
萌比男神i
萌比男神i 2021-01-28 05:19

I\'ve managed to make simple voting system with single current score. Everything is fine but the problem is that when I click on a button to vote for this particular

相关标签:
2条回答
  • 2021-01-28 05:36

    You can't use $(this) inside success function as it will changes with context in which $(this) is called, you have to store the it in a var and then use it like below in your ajax success:

    <script type="text/javascript">
        $(function () {
            $(".vote").click(function ()
            {
                var id = $(this).attr("id");
                var name = $(this).attr("name");
                var dataString = 'id=' + id;
                var acdc = $('#ab').attr('class');
                var potato = 'potato';
                var parent = $(this);
    
                if (name == 'up')
                {
                    $.ajax({
                        type: "POST",
                        url: "up_vote.php",
                        data: dataString,
                        cache: false,
                        success: function (html) {
                            parent.parent().find('.this').html(html);
                        }});
                }
                else
                {
                    $(this).fadeIn(200).html('<img src="img/icon-down.png" align="absmiddle"     style="height: 10px;width:10px;">');
                    $.ajax({
                        type: "POST",
                        url: "down_vote.php",
                        data: dataString,
                        cache: false,
                        success: function (html) {                        
                            parent.parent().find('.this').html(html);
                        }});
                }
                return false;
            });
    
        });
    </script>
    
    0 讨论(0)
  • You haven't shown the code, but presumably the AJAX request is fired on click of a .vote element. If this is the case you can store a reference to the element which raised the event, then use DOM traversal to find the sibling .this and change it's HTML. Something like this:

    $('.vote').click(function(e) {
        e.preventDefault();
        var $vote = $(this); // store the element which raised the event here
        $.ajax({
            url: 'foo.php',
            success: function(html) {
                $vote.siblings('.this').html(html); // use siblings() to find .this to change
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题