开发者

Jquery add html() for individual elements

I'm loading an ajax-loader gif whenever a voting button is clicked. The image however appears for all items. I'm trying to find out how to load the image just for the item I voted. This is my code.

$(document).ready(function(){
    $(".vote").cli开发者_运维百科ck(function(e) {
       $('.ajax_load').html('<img src="/images/ajax-loader.gif" />');
       var item_id = $(this).attr("id");
       var dataString = 'item_id=' + item_id;

    $.ajax({
        type: "POST",
        url: "vote.php",
        data: dataString,  
        cache: false,
        success: function(html) {
     $('.ajax_load').html('Voted!');
        }
    });
    return false;
});
});

HTML sample

<div class="vote" id=88">Vote</div> <div class="ajax_load">
<div class="vote" id=92">Vote</div> <div class="ajax_load">
<div class="vote" id=38">Vote</div> <div class="ajax_load">


From the html sample, it looks like the elements are siblings so you should use

$(this).nextAll('.ajax_load:first').html('<img src="/images/ajax-loader.gif" />');

to show the image.

in the success callback use

$('#' + item_id).nextAll('.ajax_load:first').html('Voted!');

to target the specific voted element.


I suppose there are several elements having the class ajax_load. You need to somehow identify them uniquely. Take a look at the explanations in these questions:

  • How to show a hidden div on mouse over on a series of images
  • jquery individual mouseenter for elements


Assuming .ajax_load is a child of vote, then you can change this:

$('.ajax_load').html('<img src="/images/ajax-loader.gif" />');

to:

   $(this).find('.ajax_load').html('<img src="/images/ajax-loader.gif" />');

That will only effect the .ajax_load that is a child of the vote that was clicked, and not all of them.

Same thing in your ajax call. I believe $(this) should still refer to the clicked "vote".

$('.ajax_load').html('Voted!');

Becomes...

$(this).find('.ajax_load').html('Voted!');

edit Okay, given that html, there are a couple of ways to do this. I would probably do it this way:

$(this).next('.ajax_load:first')...  <- do whatever you'll do with the selection.

Generally, if you're trying to figure out how to select a div using JQuery, a great place to look is the Jquery documentation for traversing and selecting.


You can try this:

$("vote").click(function(e) {
    $(this).html(...);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜