简体   繁体   中英

Use JavaScript variable as iframe src?

I'm trying to use a JavaScript variable as the src in a <iframe> , the user will then be able to load other content by choosing scr in a menu, which changes the variable. the default src URL is apps/start.php .

Here some code from my index.php :

    <script>
        var appurl = "start.php";
        document.getElementById("app").src = "apps/" + appurl();
    </script>

    <iframe id="app" src="">

    </iframe>

The problem is that i can't get this first small part working... The <script> tag is in the <head> . And when the src is changing will the new document automatically load?

The problem is that the Javascript is run before the iframe is there. Put your javascript below your iFrame or inside the document ready and it will work.

Example document onload:

<script>
    window.onload = function ()
    {
        var appurl = "start.php";
        document.getElementById("app").src = "apps/" + appurl();
    }
</script>

<iframe id="app" src="">

</iframe>

Wait for the page to load (note that this is only going to work when the iframe is on your domain)

window.onload = function(){
 var appurl = "start.php";
 document.getElementById("app").src = "apps/" + appurl;
};
<script>
    window.onload = function ()
    {
        var appurl = "start.php";
        document.getElementById("app").src = "apps/" + appurl;
    }
</script>

<iframe id="app" src="">

</iframe>

Try

<script>
window.onload = function(){
 var appurl = 'start.php';
 document.getElementById("app").src = "apps/" + appurl;
};
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM