undo-preventDefault()或以编程方式禁用链接集合的更好方法

undo preventDefault() or better way to programmatically disable collections of links

本文关键字:集合 链接 更好 方法 方式禁 编程 undo-preventDefault      更新时间:2023-09-26

我有一个页面,其中包含网络状态的事件侦听器。当网络处于"脱机"状态时,我想禁用任何跨域链接以进入脱机模式。我试图使用.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。。。然而,我不确定这是否是最好的解决方案。

您似乎在使用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")开头。最好给这样的链接提供自己的类,就像维基百科对"外部"所做的那样。