0

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

例如:

  • google search "Wiki Born (Random number 1400-1850)" >>> 查找随机发布的黑暗时代传记

  • google 搜索“无法解释的(随机数 1900 1930)”>>> 查找随机无法解释的事件

4

1 回答 1

2

如果要在页面加载时生成带有随机数的随机链接

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;
};

如果要在页面加载时显示所有带有自己随机数的链接,请添加一个循环:

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

....

如果您希望每个链接每次点击时生成不同的数字,我们可以采取不同的方法:

<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>
于 2013-04-21T08:50:06.497 回答