Javascript 如何使用 jquery 生成和附加随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6967975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:01:43  来源:igfitidea点击:

how to generate and append a random string using jquery

javascriptjquery

提问by jon

Generalities

一般性

I'd like to append a random string to an element's attribute, using either jQuery or javascript.

我想使用 jQuery 或 javascript 将随机字符串附加到元素的属性。

Specifics

规格

I need to reference a CSS file that lives on a CDN. Unfortunately, the CDN changes the URL of this CSS file every time the file is updated. So I can't simply refer to a static URL.

我需要引用位于 CDN 上的 CSS 文件。不幸的是,每次更新文件时,CDN 都会更改此 CSS 文件的 URL。所以我不能简单地引用一个静态 URL。

It turns out tho, that if you append a string to the end of the URL that the CDN has never seen before, it will return the most recent version of the file. Bogus to be sure.

事实证明,如果您将一个字符串附加到 CDN 以前从未见过的 URL 的末尾,它将返回该文件的最新版本。假的可以肯定。

e.g.

例如

<link href="http://example.com/style.css?randomString-neverSeenBefore">

I know, this is ugly, faulty and insane. But sometimes that's how the cookie crumbles. The alternative would be to attempt to maintain, in parity, a growing battery of CSS files and template headers... not viable. ;)

我知道,这是丑陋的、错误的和疯狂的。但有时这就是饼干碎的方式。另一种方法是尝试维护越来越多的 CSS 文件和模板标题……不可行。;)

What I've got so far,

到目前为止我所得到的,

My jQuery skills are meager. I've found two different bits of code that do what I need on their own but I can't for the life of my figure out how to get them to work together.

我的 jQuery 技能很差。我发现了两种不同的代码可以独立完成我需要的工作,但我终生无法弄清楚如何让它们协同工作。

bit of code #1:

代码#1位:

        // this guy is a random number generator that i found
        jQuery.extend({
        random: function(X) {
            return Math.floor(X * (Math.random() % 1));
        },
        randomBetween: function(MinV, MaxV) {
          return MinV + jQuery.random(MaxV - MinV + 1);
        }
    });


    // using above plugin, creates 20 random numbers between 10 and 99
    // and then appends that 40 digit number to a paragraph element
    for (i = 0; i < 20; i++) {
        $('p').text(    
            $('p').text() + ($.randomBetween(10, 99) )
            );
    }

bit of code #2:

代码#2位:

    // this fellow creates a link to the style sheet
    // after the page has loaded
    var link = $("<link>");
    link.attr({
            type: 'text/css',
            rel: 'stylesheet',
            href: 'http://example.com/style.css'
    });
    $("head").append( link ); 

I assume "bit of code #2" is required: my presumption is that were I to simply appended a random number to the end of an existing "href" attribute, nothing would happen. i.e. the CSS file would notbe reloaded.

我假设需要“代码位#2”:我的假设是,如果我只是将一个随机数附加到现有“href”属性的末尾,则不会发生任何事情。即不会重新加载CSS 文件。

Thanks a million for your help on this! :)

感谢您对此一百万的帮助!:)

Jon

乔恩

回答by AlienWebguy

Adding a random string is called a cache-buster. You shouldn't do it on every page load as it completely defeats the purpose of cache.

添加随机字符串称为缓存破坏者。您不应该在每个页面加载时都这样做,因为它完全违背了缓存的目的。

To answer howto accomplish it with a random string, you can try this:

要回答如何用随机字符串完成它,你可以试试这个:

$('<link/>').attr({
                   type: 'text/css',
                   rel: 'stylesheet',
                   href: 'http://example.com/style.css?' + randString(4)
}).appendTo('head');

Here's a simple random string generator function:

这是一个简单的随机字符串生成器函数:

/**
 * Function generates a random string for use in unique IDs, etc
 *
 * @param <int> n - The length of the string
 */
function randString(n)
{
    if(!n)
    {
        n = 5;
    }

    var text = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for(var i=0; i < n; i++)
    {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return text;
}

回答by Lekensteyn

Keep it simple, apply the current timestamp in miliseconds to the URL:

保持简单,将当前时间戳(以毫秒为单位)应用于 URL:

// this fellow creates a link to the style sheet
// after the page has loaded
var link = $("<link>");
link.attr({
        type: 'text/css',
        rel: 'stylesheet',
        href: 'http://example.com/style.css?' + (new Date).getTime()
});
$("head").append( link );

Please note that this is really a bad idea, if you're not going to change your stylesheet much, just replace the URL manually in the files. There are tools for that purpose available (sedunder Linux-based systems)

请注意,这确实是一个坏主意,如果您不打算大量更改样式表,只需手动替换文件中的 URL。有可用sed于此目的的工具(在基于 Linux 的系统下)

回答by Fernando

You can get just part of the date, for example:

您可以只获取日期的一部分,例如:

var d = new Date;

// this string will change once a day for the same user
var rnd_str_day = d.getFullYear() + '_' + d.getMonth() + '_' + d.getDay();
href= 'http://example.com/style.css?' + rnd_str_day;

// this string will change once an hour
var rnd_str_hour = d.getFullYear() + '_' + d.getMonth() + '_' + d.getDay() + '_' + d.getHours();
href= 'http://example.com/style.css?' + rnd_str_hour;

And so the css will be uncached once a day or an hour, depending on your requeriments.

因此,根据您的要求,css 将每天或每小时不缓存一次。