我在一个页面上有 3 个链接。所有都有 css class="suggested_product"和一个 id,它是我需要包含在 url 中的整数。我想覆盖当你点击时发生的事情。我有一个 ajax 函数,它将发送一些我正在记录到 url 的数据,然后一旦完成,将页面重定向到原始 url。非 javascript 后备应始终转到原始 href。
我的问题是我还没有找到如何从点击函数内部获取原始 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;
});
});
建议?
最佳答案
$(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;
});
});
关于Jquery 覆盖链接,使用 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9421789/