开发者

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 to get the jQuery to work for all like buttons on the page, but uses the unique ID from each post. This may be a noob question, but thats what I am. Any sulutions you can offer will be great. Thanks!

Code:

jQuery:

<script type="text/javascript">
$(function() {
$(".like").click(function(){
$("#loading").html('<img src="loader.gif" align="absmiddle">&nbsp;loading...');

 $.ajax({
   type: "POST",
   url: "like.php?id=<?php $row['uid']; ?>", // UNIQUE ID, EVERY POST WILL HAVE ONE
   success: function(){
$("#loading").ajaxComplete(function(){}).slideUp();
$('#like'+I).fadeOut(200).hide();
$('#remove'+I).fadeIn(200).show();
}
});
return false;

});

});
</script>

<script type="text/javascript">
$(function() {
$(".remove").click(function(){
$("#loading").html('<img src="loader.gif" align="absmiddle">&nbsp;loading...');

 $.ajax({
   type: "POST",
   url: "remove.php?id=<?php $row['uid']; ?>", /// UNIQUE ID, EVERY POST WILL HAVE ONE
   success: function(){
$("#loading").ajaxComplete(function(){}).slideUp();
$('#remove'+I).fadeOut(200).hide();
$('#like'+I).fadeIn(200).show();
}
});
return false;

});

});
</script>

HTML:

<div id="follow1"><a href="#" class="follow" id="1">

<span style="font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; font-weight: bold; color:#7391AC; text-align:left; font-size:20px; text-align:left;">&nbsp;<strong>like</strong>
</span></a>
</div>

<div id="remove1" style="display:none"><a href="#" class="remove" id="1">

<span class="remove_b" style="font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; font-weight: bold; color:#7391AC; text-align:left开发者_开发技巧; font-size:20px; text-align:left;">unlike
</span></a>
</div>


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

html

<div class="box" data-id="1">
    <a href="#" class="like">like</a>
    <a href="#" 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/


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

});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜