2014-07-18 61 views
0

I have 2 htm files: a.htm and b.htm. In b.htm I have 2 divs, in one is a link to a.htm which I would like to open in second div but it opens as new page in new tab. I'm not good in javascript but I looked many examples so I believe I'm very close to solution but obviously have some error somewhere. Please help!的javascript:目標格在<a href ...>

So, in a.htm I have this:

<html> 
    <body> 
     TEST 
    </body> 
</html> 

In b.htm I have this:

<html> 
    <head> 
     <script language="JavaScript"> 
      function url2div(url,target){ 
       document.getElementById(target).innerHTML = '<iframe style="width:100%;height:100%;" frameborder="0" src="' + url + '" />'; 
      } 
     </script> 
    </head> 
    <body> 

     <div id="menu" style="background-color:#FFD700;height:100px;width:100px;float:left;"> 
      <a href="a.htm" onclick="url2div(this.href,'content')">Click</a> 
     </div> 

     <div id="content" style="background-color:#EEEEEE;height:100px;width:400px;float:left;"> 
      Original content 
     </div> 

    </body> 
</html> 

回答

3

Store your link inside the function instead of the href attribute:

<a href="#" onclick="url2div('http://www.bing.com', this)">Click</a> 

Change JS to this:

function url2div(url, element) { 
    var iframe = document.createElement('iframe'); 
    iframe.setAttribute('src', url); 
    element.appendChild(iframe); 
} 

JSFiddle Demo #1

如果你想在同一 iframe打開鏈接,存儲在比 href以外的任何其他財產的鏈接

。然後,使用你當前的功能,它應該工作得很好!

<a href="#" id="a.htm" onclick="url2div(this.id,'content')">Click</a> 

JSFiddle Demo #2

+0

爲什麼你擺脫的第二個參數的功能?如果他們想在多個獨立的div中使用這種技術呢? – RevanProdigalKnight

+0

好點..更新了答案:)謝謝@RevanProdigalKnight – imbondbaby

0

我想,你讓這個並不複雜。此外,以前的答案不完全是做什麼OP是問...所以這裏是我的刺:

首先,我假設html5,所以你不需要「JavaScript」作爲腳本的一部分標籤。其次,我不認爲你需要傳遞所有這些變量。你的錨標記應參考

<a href=b.htm#content onclick="url2div();"<\a> 

而JavaScript應該是

otherPageText = "<iframe src=\"HtmlPage2.html\" width=\"200\" height=\"200\"></iframe>"; 
    document.getElementById("content").innerHTML = otherPageText; 

之後,如果你需要的變量,仔細試圖通過他們一次一個。

原問題的部分原因是,你傳遞「這個」,它引用了新的一頁,而不是舊的,但這種情況發生的時候,你是新的頁面上,而不是把在你想要的回到第一頁。我爲什麼遠離它的部分原因。

PS很抱歉的壞格式。這是非常新的給我...