改变iframe源即使用javascript

15 iframe jquery

我使用了iframe,如下所示:

<iframe style='width: 330px; height: 278px' scrolling='no' name="iframeId" class="advPlayer" id="iframeId" frameborder="0" src='../../player/iabpreview.php?adid=<?php echo $selectedAdIdx ?>&amp;autoPlay=true'></iframe>
Run Code Online (Sandbox Code Playgroud)

每当我点击a时<div>,我都要更改iframe的来源.我使用以下代码:

if ($j.browser.msie) {            
  frames['iframeId'].window.location="../player/iabpreview.php?adid="+adId+"&autoPlay=true";
}else {
  $j(".advPlayer").eq(0).attr("src", "../player/iabpreview.php?adid="+adId+"&autoPlay=true");    
}
Run Code Online (Sandbox Code Playgroud)

这适用于Firefox,但不适用于Internet Explorer.

什么代码也适用于Internet Explorer?

小智 25

您永远不应该使用"浏览器检测",而是要检测功能.imho最安全的方式是:

function SetIFrameSource(cid, url){
  var myframe = document.getElementById(cid);
  if(myframe !== null){
    if(myframe.src){
      myframe.src = url; }
    else if(myframe.contentWindow !== null && myframe.contentWindow.location !== null){
      myframe.contentWindow.location = url; }
    else{ 
      myframe.setAttribute('src', url); 
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

只测试src属性是否可用.如果没有,请在内容窗口上进行测试,最后一次尝试是setAttribute.


Kir*_*tan 14

document.getElementById("iframeId").src = "Your URL here."
Run Code Online (Sandbox Code Playgroud)

  • 咦?你100%肯定吗?这应该适用于任何broswer. (2认同)