Trying to random several links youtube videos in i

2019-09-06 10:35发布

trying to make a iframe with a random youtube links at page upload without any onclick

var glink = 0;
var games = new Array();

games[glink++] = "http://www.youtube.com/pRpvdcjkT3k";
games[glink++] = "http://www.youtube.com/Te4wx4jtiEA";

function randomglink() {
    var random = rand(glink) - 1;
    location.src = games[random];
}
<div><iframe width="283" height="242.5" src="randomglink()" frameborder="0" allowfullscreen></iframe></div>

2条回答
Luminary・发光体
2楼-- · 2019-09-06 11:24

The src attribute is not like an event (e.g. onclick ) that executes a javascript function to get its location/URL. But you can dynamically change the src attribute.

To have a script triggered on page load (without jQuery etc.)

<body onload="randomglink()">

In order to manipulate your iframe element, give it an id (has to be unique). In this example I named it videoFrame:

<div><iframe id="videoFrame" width="283" height="242.5" src="" frameborder="0" allowfullscreen></iframe></div>

Then from your script, set the src attribute:

function randomglink() {
    var random = rand(glink) - 1;
    document.getElementById('videoFrame').src = games[random];
}
查看更多
看我几分像从前
3楼-- · 2019-09-06 11:25

this help you :

<html>
<head>
</head>
    <body>
        <div>
            <iframe id="ifo" width="283" height="242.5" frameborder="0" allowfullscreen>
        </iframe>
        </div>
        
        <script>
                var glink = 1;
                var games = new Array();

                games[glink++] = "http://www.w3schools.com";
                games[glink++] = "https://mail.google.com";

                function randomglink() {
                     var randomNum =Math.floor((Math.random() * 2) + 1); 
                     document.getElementById("ifo").src = games[randomNum];
                }
            randomglink();
        </script>
    </body>
</html>

查看更多
登录 后发表回答