如何为所有链接编写同一个请求脚本?

我是jQuery AJAX新手。我想建立一个书签系统,例如Twitter做的收藏夹),但是我为每个链接编写的AJAX请求都没有用,所以我只想对所有链接使用一个请求脚本。 假设我有一些链接,链接如下:

<a href="#" id="1"><i class="icon-star-empty"></i></a>
<a href="#" id="2"><i class="icon-star"></i></a>
<a href="#" id="3"><i class="icon-star-empty"></i></a>

我想编写一个AJAX请求,当用户单击其中一个URL时,它会执行类似的操作:

if (class="icon-star-empty"){
    ajaxURL = "/insertBoomark"
} else{
    //it means class=icon-start
    ajaxURL = "/deleteBookmark"
}

$.ajax({
  url: ajaxURL,
  type: "POST",
  data: {id : linkID}, // I don't know how to get linkID too :(
  success: if class was icon-star empty then change it to icon-star-empty else change it to icon-star
});

我知道这个语法不正确,可是我该怎么解决这个问题? 请帮帮我吧。

Okay, first, class is a reserved name in javascript.

Secondly, if you're doing it with a jQuery.click function, then you can just do $(this).attr('id') to get the id.

Also, for the success part, you seem to be confused about javascript's function syntax. What exactly are you trying to do?

$("i").on("click", function() {

    if ( $(this).hasClass("icon-star-empty") ){
        ajaxURL = "/insertBoomark"
    } else{
        //it means class=icon-start
        ajaxURL = "/deleteBookmark"
    }

    var linkID = $(this).parent().prop("id");
    var obj    = $(this);

    $.ajax({
        url: ajaxURL,
        type: "POST",
        data: {id : linkID},
        success: function() {
            obj.hasClass("icon-star") ? obj.removeClass("icon-star").addClass("icon-star-empty") : obj.removeClass("icon-star-empty").addClass("icon-star");
        }
    });
})

You can also use the href attribute and just prevent the default action from the jquery event.

html

<a href="page1" class="icon-star-empty"></a>
<a href="page2" class="icon-star"></a>
<a href="page3" class="icon-star-empty"></a>

javascript

    $(function(){
        $(document).on('click','a',function(e){
            e.preventDefault(); //prevent default click action
            var $this = $(this);  // keeps "this" accessable
            var ajaxURL = $this.attr('href'); // get the url from the "a" tag
            $.ajax({
                url: ajaxURL,
                type: "POST",
                data: {id : linkID},
                success: function() {
                    if($this.hasClass("icon-star"))
                        $this.removeClass("icon-star").addClass("icon-star-empty");
                    else
                        $this.removeClass("icon-star-empty").addClass("icon-star");
                }
            });
        });
    });
$('a').click(function(){
    var _ajaxURL,
    _self = $(this);
    if($(this).hasClass('icon-star-empty')){
        _ajaxUrl = "/insertBookmark";
    }else{
        _ajaxUrl = "/deleteBookmark";
    }
    $.ajax({
        url: _ajaxUrl,
        type: 'POST',
        data: {id : $(this).prop('id')},
        success: {
           //I have no idea what you want to do right here.
        }
    });
});