使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:26:01  来源:igfitidea点击:

change the src of an iframe using javascript

javascriptiframe

提问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 divand append the iframe srcbased on the cell's value. When the user clicks on the cell again the iframebecomes blank and the divis hidden.

我希望能够点击表格中的任何单元格,获取里面的值,显示div并附加iframe src基于单元格的值。当用户再次单击单元格时,该单元格iframe变为空白并div隐藏。

For example: click cell one, show the divwith the iframe src="/one.html". Click it again, hide the div with a blank iframe.

例如:点击单元格one,显示出diviframe src="/one.html"。再次单击它,用空白隐藏 div iframe

Thanks in advance!

提前致谢!

(Please, no jQuery answers.)

(拜托,没有 jQuery 答案。)

回答by rekire

Without adding an id to the iframeuse 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 onclickevent of tdand pass desired srcin parameter.

它应该类似于下面的内容。在onclick事件发生时调用此函数tdsrc在参数中传递所需的内容。

  <script type=”text/javascript”>
    function changeURL(srcvalue)
    {
    document.getElementById('letters').src=srcvalue;
    }
    </script>