5

我有一个页面,其中包含网络状态的事件侦听器。当网络“离线”时,我想禁用任何跨域链接以进入离线模式。我试图使用.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()呼叫或更好的方法来完成这项任务?

可能的解决方案


My initial thoughts were either having store an array of the href values and then remove/add. I have been playing around with the HTML5 storage using webdb's I could create a database for and dynamically pull the hrefs onclick...however I'm not sure if this is the best solution for this.

4

1 回答 1

9

You seem to be using jQuery, at least for the link handler part.

The thing to realize is that $.click(handler) is just shorthand for .bind('click', handler). If you define the handler elsewhere, you can also unbind it later, like this:

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);

By the way, href^="http" is a bit fragile, if you only want this to happen to external links. Internal links might start with "http", and some external links could start with other protocols like "ftp". Better to give such links their own class, like Wikipedia does with 'external'.

于 2011-06-14T05:06:36.407 回答