2013-10-24 37 views
0

在我的網站上,我有一個jQuery腳本淡入頁面主體,然後當用戶單擊相對鏈接時,主體淡出並將用戶重定向到新頁面,該腳本然後再次啓動。如何使用jQuery將頁面重定向到iframe

我的同事建議我最好將主要內容放入iframe中,以便在更改頁面時不會讓整個身體更新,但問題在於,當用戶單擊相對鏈接時,iframe會褪色出來,而不是新的頁面定位的iframe它只是打開了頁面。

我該如何解決這個問題?我認爲錯誤發生在$("body").fadeIn(2000);之後。

<script type="text/javascript" src="jquery-2.0.3.min.js"></script> 
    <script type="text/javascript"> 
    $(document).ready(function() { 
     $("body").css("display", "none"); 
     $("body").fadeIn(2000); 
     $(".transition").click(function (event) { 
      event.preventDefault(); 
      linkLocation = this.href; 
      $("iframe").fadeOut(1000, redirectPage); 
     }); 

     function redirectPage() { 
      window.location = linkLocation; 
     } 
    }); 
    </script> 

    <a href="competition.html" class="transition" target="iframe">Home</a> 

    <iframe src="main.html" name="iframe" seamless="seamless" width="800" height="800"> 
    </iframe> 
+0

爲什麼不使用separete divs(節)爲此?把你需要的所有東西放在一個頁面上,並根據需求顯示/隱藏它 – paka

+0

我剛剛嘗試過,你的代碼工作正常,點擊相關鏈接,我在iframe中獲得一個新頁面。 –

+0

在iframe中打開的內容不包含鏈接,僅包含文本。所有相關鏈接都在父頁面上。如果你做了我所做的事情並且工作,我將不得不回去再試一次。 – RoyalSwish

回答

0

,因爲很多時候它是不允許你不能改變的iframe窗口的位置得到HREF。由於安全原因 有些網站設置的X架-選項SAMEORIGIN您可以測試這一點,只是改變

//your syntax is wrong here see below for correct 

window.location = linkLocation

//correct way to change the location of iframe window 

window.frames['yourframeName'].location=linkLocation

<a>「 s鏈接hrefhttp://www.google.com

現在在控制檯中看到錯誤。

因此,你的語法是錯誤的,你不改變你的iframe的位置,你正在改變包含目標iframe的主頁面(窗口)的loacation。因此,完成您的工作的更正是

function redirectPage() { 
     $('iframe').attr('src',linkLocation); 
     $('iframe').fadeIn() 
    } 
+0

對,你的建議有效......有點。我現在可以將iframe的源代碼更改爲新頁面 - 但現在,當我單擊另一個相關鏈接時,iframe的源代碼保持不變。 編輯 - 我找到原因。我點擊了包含iframe的頁面的鏈接,因此腳本被卡住了。出於測試目的,我將href更改爲google,並且腳本正常工作!在接受您的解決方案之前,我會在我的實際網站上驗證您的答案。 – RoyalSwish

0

使用document.getElementById("iframe").src改變的iframe src屬性,並將其設置爲被點擊鏈接的href。

而且你應該使用$(this).attr("href");

<script type="text/javascript" src="jquery-2.0.3.min.js"></script> 
    <script type="text/javascript"> 
    $(document).ready(function() { 
     $("body").css("display", "none"); 
     $("body").fadeIn(2000); 
     $(".transition").click(function (event) { 
      event.preventDefault(); 
      linkLocation = $(this).attr("href"); 
      $("iframe").fadeOut(1000, redirectPage(linkLocation)); 
     }); 

     function redirectPage(url) { 
      document.getElementById("iframe").src = url; 
     } 
    }); 
    </script> 

    <a href="competition.html" class="transition" target="iframe">Home</a> 

    <iframe src="main.html" id="iframe" name="iframe" seamless="seamless" width="800" height="800"> 
    </iframe> 
相關問題