简体   繁体   中英

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").click(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.

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 .

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:

You can try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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