JavaScript - 将随机数/变量插入动态超链接?

时间:2013-04-21 07:53:44

标签: javascript html random hyperlink

这是我的第一个HTML JavaScript,我希望通过包含半随机单词和数字的JavaScript生成随机HTML链接,以搜索随机知识/神秘文章。

例如:

  • 谷歌搜索“Wiki Born(随机数1400-1850)”>>>随机查找 发布黑暗时代的传记

  • google search“unexplained(Random number 1900 1930)”>>>随机查找 无法解释的事件

1 个答案:

答案 0 :(得分:2)

如果你想要generate a random link with a random number on page load

var searches = [
    ['Wiki Born', 1400, 1850, 'post dark ages biography'],
    ['unexplained', 1900, 1930, 'unexplained event']
];
var google = "http://www.google.com/search?q=";

function getRand(min, max) {
    return min + Math.floor(Math.random() * (max-min));
}

window.onload = function() {
    // get random search item
    var item = searches[getRand(0, searches.length)];

    // get random number based on the selected item
    var randnum = getRand(item[1], item[2]);

    // put together the google link, replace spaces with + sign
    var searchlink = (google + item[0] + ' ' + randnum).replace(/\s+/g, '+');
    console.log(searchlink);

    // put together the html tag
    var html = '<a href="'+searchlink+'" target="_blank">Find random '+item[3]+'</a>';
    console.log(html);

    document.body.innerHTML = html;
};

如果您想要display all links with their own random number on page load,请添加循环:

// for each search item
for(i=0; i<searches.length; i++) {
    var item = searches[i];

....

如果您需要each link to generate a different number each time it is clicked,我们可以采用不同的方法:

<script>
function getRand(min, max) {
    return min + Math.floor(Math.random() * (max-min));
}

window.onload = function() {
    // get all links in the #randomlinks div
    var links = document.getElementById('randomlinks').getElementsByTagName('a');

    // for each search item
    for(i=0; i<links.length; i++) {

        // set a click handler
        links[i].onclick = function() {

            // get random number based on data attributes
            var min = parseInt(this.getAttribute('data-min'), 10);
            var max = parseInt(this.getAttribute('data-max'), 10);
            var randnum = getRand(min, max);

            // append random number to end of link
            this.href = this.href.replace(/\+[0-9]*$/, '+'+randnum);
        };
    }
};
</script>
<div id="randomlinks">
    <a href="http://www.google.com/search?q=Wiki+Born+" data-min="1400" data-max="1850" target="_blank">Find random post dark ages biography</a><br>
    <a href="http://www.google.com/search?q=unexplained+" data-min="1900" data-max="1930" target="_blank">Find random unexplained event</a>
</div>