我可以在preventDefault()之后执行链接吗?

mar*_*zzz 11 jquery

代码:

$('#myLink').click(function (e) {
    e.preventDefault();

    ...

    if (someCondition) {
        ... code ...
    } else {
        ... execute the link
    }
});
Run Code Online (Sandbox Code Playgroud)

我想,如果someCondition是假的话,执行链接的原始href(所以,去那个链接,改变页面).这有可能吗?

coo*_*guy 19

$('#myLink').click(function (e) {
    e.preventDefault();

    ...

    if (someCondition) {
      //do stuff
    } else {
        location.href = $(this).attr('href');
    }
});
Run Code Online (Sandbox Code Playgroud)


Mot*_*tie 6

只需preventDefault在if/else语句中移动:

$('#myLink').click(function (e) {

    ...

    if (someCondition) {
        e.preventDefault();

        ... code ...

    } else {
        ... execute the link
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 是的,因为答案是错误的并且具有误导性. (5认同)
  • 根据您的条件需要多长时间,浏览可能会在到达代码的这一部分之前跟随原始链接. (3认同)