我有一个大概'简单'的任务,绝对是踢我的屁股。
我的目标是当用户单击链接时,我阻止默认值,在其上运行 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')是否在数组中,如果是,则将其删除。此数据 ID 与 Wordpress 中帖子的 ID 相关,当用户点击指向该帖子的链接时,需要将其删除。
因此 - 用户单击链接,检查数据 ID,从数组中删除/未删除,跟踪链接。
首先给你的 href 一个 ID,如下所示:
<a href="some_href" data-id="789" id='#some-link'>This is the link</a>
然后在ajax成功部分中模拟点击它:
...
success: function(response) {
$('#some-link').click();
})
...
您可以在触发点击之前检查response
。另外,我认为您不需要.then
等等。