Open link from variable in iframe

2019-08-29 11:40发布

问题:

    <script language="Javascript" type="text/javascript">
    function Next(){
        var randp = Math.floor(Math.random()*3);
        switch(randp){
            case 0:
                var websel = "http://w3schools.com";
                break;  
            case 1:
                var websel = "http://www.bbc.com/";
                break;
            case 2:
                var websel = "http://en.wikipedia.org/wiki/BBC";
                break;
            default:
                document.write("Error SWITCH(randp) " + randp + " ");
                break;
        }
    }
    </script>

    <iframe name="iframea" src="http://w3schools.com" seamless="seamless" scrolling="auto" height="560px" width="1080px" align="middle" scale="1.5"></iframe> 

 <input type="button" value="Next" onClick="Next()">

Sorry for the basic question. What would I need to add to have the next button open a link (the link being a variable from a function) with the target as the iframe. Thanks

回答1:

You have to change the src of your iframe as following:

        <script language="Javascript" type="text/javascript">
        function Next(){
            var randp = Math.floor(Math.random()*3);
            switch(randp){
                case 0:
                    var websel = "http://w3schools.com";
                    break;  
                case 1:
                    var websel = "http://www.bbc.com/";
                    break;
                case 2:
                    var websel = "http://en.wikipedia.org/wiki/BBC";
                    break;
                default:
                    document.write("Error SWITCH(randp) " + randp + " ");
                    break;
            }
            alert(websel);
            document.getElementById("iframea").src=websel;
        }
        </script>

        <iframe name="iframea" id="iframea" src="http://w3schools.com" seamless="seamless" scrolling="auto" height="560px" width="1080px" align="middle" scale="1.5"></iframe> 

     <input type="button" value="Next" onClick="Next()">

By the way, you might look on this website this question is similar.