【问题标题】:Change iFrame Src with Javascript, JQuery, Dynamically [duplicate]使用 Javascript、JQuery、动态更改 iFrame Src [重复]
【发布时间】:2014-09-08 20:07:58
【问题描述】:

过去几个小时我一直在尝试更改 iFrame 的 src。这似乎是一项简单的任务,但由于某种原因,经过数百次尝试并阅读了堆栈上的许多其他问题和答案,我仍然发现自己无法更改 iFrame 的 src。正如您从下面的代码中看到的那样,我已经尝试了很多次。我做错了什么?

    <body>

       <p><iframe src="http://localhost/ok.html" name="myFrame" width="500" marginwidth="0"     height="500" marginheight="0" align="middle" scrolling="auto"></iframe>


<script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
    function loadPages(){
        var loc = "http://localhost/morningmarketweb/index.html";

        //var myIframe = document.getElementById("myFrame");

        //window.frames[myIframe].location = "http://localhost/morningmarketweb/index.html";

        // $(myIframe).load('http://localhost/morningmarketweb/index.html');

        // document.getElementId('myFrame').src="google.com";

       // var myIframe = document.getElementById('myFrame');
       // myIframe.src=loc;


        //$('#myFrame').attr('src', loc);

        document.getElementById('myFrame').setAttribute('src', loc);


    }
    </script>
    </body>

【问题讨论】:

  • 你的iframe中没有id属性myFrame
  • @Garis & Ben:如果我问“我做错了什么”,这不能重复。如果它是重复的,那么你是在说这些其他人以某种方式提前知道,深入未来,我会问我会做错什么。我认为这是不可能的。
  • 拉希尔,没错。我一直在看名字。我检查了一百万次,但从未发现 id="myFrame" 丢失。

标签: javascript jquery iframe


【解决方案1】:

名称不是 ID。设置 Id="myFrame" 这将起作用: $('#myFrame').attr('src', loc);

【讨论】:

    【解决方案2】:
    <iframe src="http://localhost/ok.html" name="myFrame" width="500" marginwidth="0"     height="500" marginheight="0" align="middle" scrolling="auto" id="myFrame"></iframe>
    
    <script>
    
    document.getElementById('myFrame').src = "http://someurl.com";
    
    </script>
    

    // 同样基于您上面的代码,您的 iframe 上没有 ID - 所以我添加了 id='myIframe'

    【讨论】:

      【解决方案3】:

      代码如下:

      <iframe src="http://jquery.com/" id="myFrame" width="500" marginwidth="0" height="500" marginheight="0" align="middle" scrolling="auto"></iframe>
      <button onclick="loadPages()">Click Me</button>
      <script>
          function loadPages(){
              var loc = "http://es.learnlayout.com/display.html";
              document.getElementById('myFrame').setAttribute('src', loc);
          }
      </script>
      

      如您所见,第一个问题是您通过 Id 请求一个元素......好吧,那么您需要指定一个 Id。第二个问题,您需要有一个触发“loadPages”操作的元素...这样您就可以为其设置一个按钮。

      这里也是函数示例:

      http://jsfiddle.net/littapanda/Jsc4E/

      【讨论】:

      • 对我来说太棒了!
      猜你喜欢
      • 2023-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 2014-06-19
      • 1970-01-01
      • 2013-02-23
      相关资源
      最近更新 更多