Change iFrame Src with Javascript, JQuery, Dynamic

2020-03-31 08:42发布

问题:

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>

回答1:

Here is the code:

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

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/



回答2:

name is not Id. Set Id="myFrame" and this will work: $('#myFrame').attr('src', loc);



回答3:

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

// also based on your code above , you didn't have an ID on your Iframe - so i added id='myIframe'