【问题标题】:How to continue with the click event after deleting it with preventDefault method? [duplicate]使用 preventDefault 方法删除 click 事件后如何继续? [复制]
【发布时间】:2023-04-01 15:35:01
【问题描述】:

我有一个链接,我用 .preventDefault 方法取消了“点击”事件,以检查用户是否登录。如果用户使用正确的角色登录,我想继续点击链接后的点击效果,回家?

jQuery('.btn-read-more').on('click', function(e) {
    e.preventDefault();
    console.log(e.currentTarget);
    var data = {
        action: 'is_user_logged_in'
    };

    jQuery.post(ajaxurl, data, function(response) {
        console.log(response);
        if (response === 'no') {
            jQuery('#modal_login_form_div').modal('show');
        } else if (response === 'ccwdpo_user' || response === 'ccwdpo_customer') {
            //e.currentTarget.click();
            //console.log(e.currentTarget);
            window.location = jQuery(this).attr("href");    
        }
    });
});

现在,我解决了:

jQuery('.permalink').on('click', function(e) {
    e.preventDefault();
    var data = {
        action: 'is_user_logged_in'
    };

    var permalink = jQuery(this).attr('href');
    //console.log(permalink);
    jQuery.post(ajaxurl, data, function(response) {
        console.log(response);
        if (response === 'no') {
            jQuery('#modal_login_form_div').modal('show');
        } else if (response === 'ccwdpo_user' || response === 'ccwdpo_customer') {
            window.location = permalink;
        } else {
            jQuery('#modal_error_div').modal('show');
        }
    });
});

【问题讨论】:

  • this 不是您认为的 post 回调中的内容。在帖子外存储对thishref 的引用

标签: javascript jquery events onclick preventdefault


【解决方案1】:

这会做你想做的事。从事件中获取href值并设置window.location

document.querySelector('a').onclick = ev => {
  // Prevent default
  ev.preventDefault();
  // Continue with action (note this does not handle if other attributes, such as `target="_blank"` is set)
  window.location = ev.target.getAttribute('href');
};
<a href="https://stackoverflow.com">Go to google</a>

【讨论】:

  • 我不明白为什么会出现无限循环... :(
  • 你在哪里得到一个无限循环?
猜你喜欢
  • 1970-01-01
  • 2018-10-14
  • 2012-03-15
  • 2013-07-04
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2014-04-18
  • 1970-01-01
相关资源
最近更新 更多