【问题标题】:undo preventDefault() or better way to programmatically disable collections of links撤消 preventDefault() 或以编程方式禁用链接集合的更好方法
【发布时间】:2011-06-14 04:49:21
【问题描述】:

我有一个页面,其中包含网络状态的事件侦听器。当网络“离线”时,我想禁用任何跨域链接以进入离线模式。我尝试使用.preventDefault(),但是当应用重新上线时,我需要重新启用链接。

事件监听器

//check network status
if(!navigator.onLine) { 
    offlineLinks(); //Offline mode function
}
//add event listeners for network status
window.addEventListener('offline', function(e) {
    offlineLinks(); //Offline mode function
}, false);
window.addEventListener('online', function(e) {
    //need to re-enable links/Online mode
}, false);
window.addEventListener('error', function(e) {
    alert('Error fetching manifest: there is a good chance we are offline.');
    offlineLinks(); //Offline mode function
});

“解除链接”功能

function offlineLinks() {
    $('a[href^="http"]').click(function(e) {
        e.preventDefault();
        $('#offline-dialog').dialog({
            modal: true,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                }
            }
        });
    });
}

我正在寻找一种可扩展的解决方案,该解决方案在页面上有大量链接时不会造成延迟。是否有一个简单的解决方案来逆转.preventDefault() 调用或完成此任务的更好方法?

可能的解决方案


我最初的想法是存储一组 href 值,然后删除/添加。我一直在使用webdb 使用 HTML5 存储,我可以为它创建一个数据库并动态拉取 hrefs onclick...但是我不确定这是否是最好的解决方案。

【问题讨论】:

    标签: javascript jquery html preventdefault offlineapps


    【解决方案1】:

    您似乎在使用 jQuery,至少对于链接处理程序部分而言。

    要意识到的是 $.click(handler) 只是 .bind('click', handler) 的简写。如果你在别处定义了处理程序,你也可以在以后解除绑定,像这样:

    var handler = function(event) { 
      event.preventDefault();
      console.log("the links, they do nothing!");
    }
    
    // when you want the external links to be inactive.
    // you could use .click(handler) here too, it's the same.
    $('a[href^="http"]').bind('click', handler);
    
    // when you want them back
    $('a[href^="http"]').unbind('click', handler);
    

    顺便说一句,href^="http" 有点脆弱,如果您只想在外部链接上发生这种情况。内部链接可能以“http”开头,而一些外部链接可能以“ftp”等其他协议开头。最好给这些链接自己的类,就像维基百科对“外部”所做的那样。

    【讨论】:

    • 类似的解决方案将涉及.bind("click:offline", f).unbind("click:offline")
    猜你喜欢
    • 1970-01-01
    • 2021-02-13
    • 2013-04-11
    • 2019-03-08
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    相关资源
    最近更新 更多