2012-05-01 24 views
1

我試圖使用jquery構建以下操作: 當用戶單擊鏈接時,mainContent div被隱藏並顯示exitSite消息。用戶然後有兩種選擇:返回到主要內容或繼續並離開網站。試圖構建jquery interstital div,但在點擊鏈接時沒有任何操作

當前問題:點擊將離開網站的鏈接時,什麼都不會發生。

這裏是我的代碼至今:

JQuery的:

$(function(){ 

if($('div#exitSite')) 
{ 
    var mydomain$ = location.hostname; 
    var links = $('a').each(function() 
    { 
     if((this.href.indexOf("mySiteDomain")==-1) && (this.href.indexOf(mydomain$)==-1) && (this.href.indexOf("javascr")==-1)) 
      $(this).addClass('exit'); 
    }); 

    /*Off site links.*/  
    $('a.exit').live('click', function (e) { 
     e.preventDefault(); //stop the click from going through. 
     var page = $(this).attr("href") //get destination page 
     var pagetitle = $(this).attr("title") 

     $('#mainContent').hide(); //hide main content window 
     $('#mainContent').show(); //show main content window 

     $('#exitSiteClose').click(function() { 
      $('#exitSite').hide(); 
      $('#mainContent').show(); 
      return false 
      }); // end click #exitSiteClose 

     $('#exitSiteContinue').click(function() { 
      window.location=page 
      //if user selects the continue button, then pass in the destination page from link. 
      }); // end click #exitSiteContinue  
    });// end click a.exit 
} 
}); 

的HTML:

鏈接離開現場: click to stackoverflow.com

退出網站div:

<div id="exitSite"> 
<h2>Hello!</h2> 
<p><strong>You are leaving this website</strong></p> 
    <div class="buttonContainer"> 
    <a href="#" id="exitSiteClose" class="btn-gray">Cancel</a> 
    <a href="#" id="exitSiteContinue" class="btn-blue">Continue</a> 
</div><!-- /.buttonContainer --> 
</div><!-- /#exitSite --> 

回答

0

您可以簡單地使用JavaScript confirm()。這不是時尚,但它是最普遍的做法,你想要的。

$('a[href^="http://"]').on('click', function(e) { // apply to all external URLs 
    return window.confirm('Are you sure you want to leave this site?'); 
}); 

從廣義上講,任何JavaScript函數,將return false;從一個單擊處理程序將取消該次點擊,而這將return true;允許它繼續下去。

一個較少侵入,更常見的方法是將target="_blank"添加到任何外部鏈接。這將在新的標籤頁/窗口中打開該鏈接,讓您的網站在單獨的網站中打開。

+0

我希望我可以,但不幸的是,客戶希望在頁面內的div ...感謝您的建議,但! –

0

您的代碼中有一個基本的拼寫錯誤。你是不是顯示你#exitSite格都:

$('#mainContent').hide(); //hide main content window 
$('#mainContent').show(); //show main content window 

需要是:

$('#mainContent').hide(); //hide main content window 
$('#exitSite').show(); //show exit confirmation window 

演示:http://jsfiddle.net/jtbowden/fhFxU/1/

要調試,我用console.log("debug")單擊處理內部和螢火觀看看看點擊處理程序是否被調用。然後,我在腦海中逐步瞭解功能,看看會發生什麼。那時候我發現你從來沒有出示過退出確認。

作爲一個方面說明,你也在處理程序中的變量定義之後缺少一對分號。

+0

Jeff B,非常感謝!我會給它一個鏡頭! –

相關問題