我有 2 个 htm 文件:a.htm 和 b.htm。在 b.htm 中,我有 2 个 div,其中一个是指向 a.htm 的链接,我想在第二个 div 中打开它,但它在新选项卡中作为新页面打开。我不擅长 javascript,但我看了很多例子,所以我相信我已经非常接近解决方案,但显然在某个地方有一些错误。请帮忙!
所以,在 a.htm 中我有这个:
<html>
<body>
TEST
</body>
</html>
在 b.htm 中我有这个:
<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>
最佳答案
将链接存储在函数内而不是 href
属性中:
<a href="#" onclick="url2div('http://www.bing.com', this)">Click</a>
将 JS 更改为:
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
关于javascript: <a href ...> 中的目标 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24825563/