0

我有以下 jQuery 似乎工作正常,除了:

$(this).attr('src', 'img/upgreen.png');

有什么理由不这样做吗?

$(function addThumbs() {
$('.vote-up').bind('click', function() {
    // 'this' is a DOM element
    // wrap 'this' in a jQuery object
    var img = $(this);
    // now we have the full jQuery API at our disposal
    var review_id = $('#review_id').val();
    var user_id = $('#user_id').val();


    if (user_id == 1) 
        { alert('...'); }
    else
     {
            $("#flash").show();
            $("#flash").fadeIn(400).html('<img src="ajax-loader.gif" />Loading Comment...');
            $.ajax({
                        type: "POST",
                        url: "ajax-thumbsup.php",
                                data:{  
                                "user_id" : user_id, 
                                "review_id" : review_id       //we are passing the name value in URL
                                },
                        cache: false,
                        success: function(html)
                            {
                            $("#progressdiv").show();
                            $("#progressdiv").fadeIn(400).html('success');
                            $(this).attr('src', 'img/upgreen.png');
                            }
                    });
    }return false;
});

});

循环内的 HTML

                                    <div class="thumbs">
                                        <input type="hidden" id="review_id" value="<?php echo $review['review_id']?>" />
                                        <input type="hidden" id="user_id" value="<?php echo $user_id ?>" />
                                        <div id="pluses">0</div> <div id="progressdiv"></div>
                                        <a><img class="vote-up" src="img/up.png" alt="thumbs up" /> </a>

                                        <a><img class="vote-down" src="img/down.png" alt="thumbs down" /> </a>
                                        <div id="minuses">0</div>
                                    </div>

                                    <div class="thumbs">
                                        <input type="hidden" id="review_id" value="<?php echo $review['review_id']?>" />
                                        <input type="hidden" id="user_id" value="<?php echo $user_id ?>" />
                                        <div id="pluses">0</div> <div id="progressdiv"></div>
                                        <a><img class="vote-up" src="img/up.png" alt="thumbs up" /> </a>

                                        <a><img class="vote-down" src="img/down.png" alt="thumbs down" /> </a>
                                        <div id="minuses">0</div>
                                    </div>
4

1 回答 1

11

thisAJAX 回调this内部与单击处理程序内部不同。

幸运的是 - 您已经保存了对它的引用!利用:

img.attr('src', 'img/upgreen.png');

注意:如果你已经保存img = this而不是img = $(this)你可以写:

img.src = 'img/upgreen.png';

无需调用 jQuery。

于 2013-05-21T17:40:14.453 回答