【问题标题】:Can I execute a link after a preventDefault()?我可以在 preventDefault() 之后执行链接吗?
【发布时间】:2012-06-12 07:32:26
【问题描述】:

代码:

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

    ...

    if (someCondition) {
        ... code ...
    } else {
        ... execute the link
    }
});

我想,如果someCondition 为假,则执行链接的原始href(因此,转到该链接,更改页面)。这可能吗?

【问题讨论】:

    标签: jquery


    【解决方案1】:
    $('#myLink').click(function (e) {
        e.preventDefault();
    
        ...
    
        if (someCondition) {
          //do stuff
        } else {
            location.href = $(this).attr('href');
        }
    });
    

    【讨论】:

    • 请注意,即使在按下 CMD (Mac) 或 CTRL (Windows、Ubuntu) 的情况下单击该链接,也会在同一选项卡中打开链接。
    【解决方案2】:

    看一看:Jquery Location Href?

    基本上你可以使用window.location.href = 'http://example.com';

    【讨论】:

      【解决方案3】:

      只需将e.preventDefault(); 放在条件中即可?

      【讨论】:

        【解决方案4】:

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

        $('#myLink').click(function (e) {
        
            ...
        
            if (someCondition) {
                e.preventDefault();
        
                ... code ...
        
            } else {
                ... execute the link
            }
        });
        

        【讨论】:

        • 取决于您的条件浏览需要多长时间,可能会在到达该部分代码之前跟随原始链接。
        • 这值得-1?哈哈好的
        • 是的,因为答案不正确且具有误导性。
        • @deweydb 那么添加一个正确且没有误导性的答案。
        • ubercooluk 的回答很好,我投了那个票。不需要再做广告了。
        猜你喜欢
        • 2023-03-08
        • 1970-01-01
        • 2012-06-09
        • 1970-01-01
        • 2023-04-02
        • 2021-11-16
        • 2023-03-04
        • 2018-03-28
        • 2012-12-01
        相关资源
        最近更新 更多