【发布时间】:2016-01-26 13:08:40
【问题描述】:
我有这个大概是“简单”的任务,这绝对让我很兴奋。
我的目标是,当用户单击链接时,我会阻止默认链接,在其上运行 ajax 函数,然后点击该链接(即恢复默认链接)。我唯一能做的就是捕获链接的href,然后使用window.location进行跟踪-这并不理想,因为它无法检测用户是选择在新窗口/标签中还是在相同的窗口/选项卡;我也认为必须有更好的方法。
但是发生的情况是默认情况被阻止,AJAX 函数运行但链接没有被跟踪。我要问的是:函数运行后如何模拟链接点击?
HTML
<a href="some_href" data-id="789">This is the link</a>
jQuery
$(document).on('click', 'a', function(e, options){
// setup our options
options = options || {};
// get some details from the link
var this_href = $(this).attr('href');
var this_id = $(this).data('id');
// if options aren't set and this link has a data-id attribute
if(!options.stuff_done && $(this_id).length){
e.preventDefault(); // prevent link following
// run some ajax
$.ajax({
url: myAjax.ajax_url,
type: 'post',
data: {
action : 'a_php_function',
post_id : this_id
},
success: function(response) {
// do stuff
}).then(function(){
$(this).trigger('click', { stuff_done: true });
});
} else {
// else if it doesn't have a data-id, do default
}
});
上下文: 使用 PHP/AJAX 检查值('data-id')是否在数组中,如果是,则将其删除。此 data-id 与 Wordpress 中的帖子 ID 相关,当用户点击该帖子的链接时需要将其删除。
因此 - 用户点击链接,数据 ID 被检查,从数组中删除/不删除,链接被关注。
【问题讨论】:
-
当有人使用中键单击或右键单击菜单在另一个选项卡或窗口中打开链接时,我认为您无法阻止默认操作。因此,您最初的解决方案可能已经达到了最佳效果。
-
编辑明确提出问题。谢谢@JayBlanchard。
-
啊,看起来 window.location 可能是最好的,也可能是唯一的方法。谢谢@jeroen。
标签: php jquery ajax preventdefault