使用 javascript 更改 iframe 的 src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8735809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
change the src of an iframe using javascript
提问by user1129274
<table>
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>three</td>
<td>four</td>
</tr>
</table>
<div id="numbers">
<iframe name="letters" src="">
</iframe>
</div>
I'd like to have the ability to click on any cell in the table, grab the value inside, show the div
and append the iframe src
based on the cell's value. When the user clicks on the cell again the iframe
becomes blank and the div
is hidden.
我希望能够点击表格中的任何单元格,获取里面的值,显示div
并附加iframe src
基于单元格的值。当用户再次单击单元格时,该单元格iframe
变为空白并div
隐藏。
For example: click cell one
, show the div
with the iframe src="/one.html"
. Click it again, hide the div with a blank iframe
.
例如:点击单元格one
,显示出div
与iframe src="/one.html"
。再次单击它,用空白隐藏 div iframe
。
Thanks in advance!
提前致谢!
(Please, no jQuery answers.)
(拜托,没有 jQuery 答案。)
回答by rekire
Without adding an id to the iframe
use this:
无需添加 id 即可iframe
使用:
document.getElementsByTagName("iframe")[0].src="http://example.com/";
Or based on the name:
或根据名称:
document.getElementsByName("letters")[0].src="http://example.com/";
If you would add a id:
如果您要添加一个 id:
<iframe name="letters" id="letterframe" src="" />
document.getElementById("letterframe").src="http://example.com/";
回答by qw3n
Added ids to some of the HTML elements.
向某些 HTML 元素添加了 id。
<table id="table">
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>three</td>
<td>four</td>
</tr>
</table>
<div id="numbers">
<iframe id="iframe" name="letters" src="">
</iframe>
</div>
And the javascript
和 javascript
document.getElementById('table').onclick=function(e){
e = e || window.event;
e=e.target || e.srcElement;
if(e.tagName.toLowerCase()=='td'){
var page = e.innerHTML,iframe=document.getElementById('iframe');
if(iframe.src.indexOf(page)>-1){
document.getElementById('numbers').style.display='none';
}
else{
document.getElementById('numbers').style.display='block';
iframe.src='/'+page+'.html';
}
}
}
回答by qw3n
It should be something like below.Call this function on onclick
event of td
and pass desired src
in parameter.
它应该类似于下面的内容。在onclick
事件发生时调用此函数td
并src
在参数中传递所需的内容。
<script type=”text/javascript”>
function changeURL(srcvalue)
{
document.getElementById('letters').src=srcvalue;
}
</script>