Jquery 覆盖链接,使用 url

Syn*_*ror 1 ajax jquery redirect

我在一个页面上有 3 个链接。所有都有 css class="suggested_product" 和一个 id,它是我需要包含在 url 中的整数。我想覆盖当你点击时发生的事情。我有一个 ajax 函数,它将发送一些我正在记录到 url 的数据,然后一旦完成,将页面重定向到原始 url。非 javascript 后备应始终转到原始 href。

我的问题是我还没有找到如何从 click 函数内部获取原始 url 或 a#id。该链接有一个图像和一个跨度,并且单击事件似乎是在这些图像而不是 a 标记上触发的。我认为。

不起作用的代码:

$(function(){
   $("a.suggested_product").click(function(e){
        e.preventDefault();
        original_url = e.target.href;
        log_url = "http://domain.com/ajax-controller/"+e.target.id;
        ajaxLogSuggestClick(log_url, original_url)
        return;
   });
});
Run Code Online (Sandbox Code Playgroud)

建议?

Jas*_*per 5

$(function(){
   $(".suggested_product").click(function(){

        //notice the use of the `var` keyword to keep variables local
        var original_url = this.href,
            log_url      = "http://domain.com/ajax-controller/" + this.id;

        //do the AJAX request to your server-side script
        $.ajax({
            url     : log_url,
            type    : 'get',
            success : function (serverResponse) {
                //successfull callback, forward user to original_url
                window.location = original_url;
            },
            error   : function () {
                //an error occured, you probably just want to forward the user to their destination
                window.location = original_url;
            }
        });

        //returning false inside a jQuery Event Handler is the same as calling `event.preventDefault()` and `event.stopPropagation()`
        return false;
   });
});
Run Code Online (Sandbox Code Playgroud)