1

我希望在单击链接时显示一个随机主页(来自预定义列表)。真的这是两个问题,所以第一个问题,这可能吗?如果是,那怎么办?

如果文件在不同的文件夹中怎么办?那么代码会像这样吗?

var arrPages = [   'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/feyra/feyra.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/rayne/rayne.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/adrienna/adrienna.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/averya/aveyra.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/demaen/demaen.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/phoenyx/phoenyx.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/raven/raven.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/trysten/trysten.html', 'http://neo.graceland.edu/~rmthomas/gothyc%20cafe/xiandre/xiandre.html'];
    document.getElementById('13').onclick = function () {
        var randUrl = arrPages[Math.floor(Math.random() * arrPages.length)];
        // Redirect/popup/new tab
        window.open(randUrl,'test');
    }
4

1 回答 1

2
// A predefined list of pages
        var arrPages =
            [
                'http://google.com',
                'http://yahoo.com',
                'http://xtra.co.nz',
                'http://asdf.com'
            ];

        // Get the element
        var aLink = document.getElementById('aLink');

        // Bind the click event of aLink
        aLink.onclick = function () {

            // Get an integer that'll determine the index of arrPages to access
            var randomInt = Math.floor(Math.random() * arrPages.length);

            // Get the element with an index of randomInt
            var randUrl = arrPages[randomInt];

            // Here you can do whatever you like with randUrl, in this case 
            //  we'll open a new window that'll point to randUrl
            //   e.g. http://xtra.co.nz
            window.open(randUrl, 'test');
        }

有关用于设置的函数的说明,randomInt 请参见Explain Math.floor(Math.random())

于 2012-11-26T00:19:31.357 回答