2014-07-18 31 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很抱歉的坏格式。这是非常新的给我...