使用Javascript,JQuery,动态更改iFrame Src [英] Change iFrame Src with Javascript, JQuery, Dynamically

查看:105
本文介绍了使用Javascript,JQuery,动态更改iFrame Src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying for the last few hours to change the src of an iFrame. It seems like a simple task but for some reason after hundreds of attempts and reading quite a few other questions and answers on stack, I still find myself without being able to change the src of an iFrame. As you can see from the code below i have attempted this quite a few times. What am I doing wrong?

    <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 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的元素......所以你可以为它设置一个按钮。

As you can see, first issue was that you are asking for an element by Id... well, then you need to specify an Id. Second issue, you need to have an element who fires the action "loadPages"... so you can set a button for it.

这也是功能性的例子:

Here is also the functional example:

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

这篇关于使用Javascript,JQuery,动态更改iFrame Src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆