撤消preventDefault或以更好的方式以编程方式禁用链接集合

问题描述

|| 我有一个页面,其中包含网络状态的事件侦听器。当网络为“离线”时,我想禁用任何跨域链接以进入离线模式。我试图使用“ 0”,但是当应用重新上线时,我需要重新启用链接。 事件监听器
//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\');
                }
            }
        });
    });
}
我正在寻找一个可伸缩的解决方案,如果页面上有大量链接,则不会造成延迟。是否有一个简单的解决方案可以撤消ѭ0调用或完成此任务的更好方法? 可能的解决方案 我最初的想法是先存储一个href值数组,然后再删除/添加。我一直在使用
webdb
来处理HTML5存储,我可以为其创建数据库并动态提取hrefs onclick ...但是我不确定这是否是最佳解决方案。     

解决方法

        您似乎至少在链接处理程序部分使用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 \”等其他协议开头。最好为此类链接提供自己的类,例如Wikipedia对\'external \'进行处理。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...