Skip to content Skip to sidebar Skip to footer

Making Multiple Ajax 'like' Button Use Same Jquery Script?

I have a Ajax 'like' button that uses jQuery, this button will be used multiple times on a page. I don't really want to include the jQuery script multiple times, so is there a way

Solution 1:

you could store the id on a containing element, and get that with each click, like so;

html

<divclass="box"data-id="1"><ahref="#"class="like">like</a><ahref="#"class="remove">remove</a><!--etc--></div>

javascript

$(function() {
    $(".like, .remove").click(function(e) {

        var id = $(this).closest('.box').data('id');
        var url = $(this).attr('class') + ".php?id=" + id;
        // a click on like will generate a url: like.php?id=1

    });
});

demo at http://jsfiddle.net/6Vrvv/

Solution 2:

Use a class and add your click function using the class like you are and you can grab the id of the clicked element.

<a href="#"id="1" class="likeMe">Like 1</a>

and

<a href="#"id="2" class="likeMe">Like 2</a>

can be targeted like:

$('.likeMe').click(function(){

  alert($(this).attr('id'));  //call your ajax stuff here with the correct id

});

Post a Comment for "Making Multiple Ajax 'like' Button Use Same Jquery Script?"