Programing

div id에 대한 임의의 문자열 생성

lottogame 2020. 11. 19. 07:44
반응형

div id에 대한 임의의 문자열 생성


내 웹 사이트에 YouTube 동영상을 표시하고 싶지만 id사용자가 공유 할 각 동영상에 대해 고유 한 동영상 을 추가 할 수 있어야 합니다. 그래서 이걸 합 쳤는데 약간의 문제가 생겼습니다. div에 임의의 문자열을 추가하기 위해 JavaScript를 얻으려고 id하지만 작동하지 않고 문자열을 표시합니다.

<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    var str = '';
    for (var i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
}

var div = randomString(8);
</script>

<div id='div()'>This text will be replaced</div>

<script type='text/javascript'>
  jwplayer('div()').setup({
    'flashplayer': 'player.swf',
    'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
    'controlbar': 'bottom',
    'width': '470',
    'height': '320'
  });
</script>

이 기능을 정말 좋아합니다.

function guidGenerator() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

에서 자바 스크립트에 GUID / UUID를 만드시겠습니까?


2018 편집 :이 답변에 흥미로운 정보가 있다고 생각하지만 실제 응용 프로그램 경우 Joe의 답변을 대신 사용해야 합니다 .

JavaScript에서 고유 ID를 만드는 간단한 방법은 Date 객체를 사용하는 것입니다.

var uniqid = Date.now();

이는 1970 년 1 월 1 일 이후 경과 된 총 밀리 초를 제공하며, 이는를 호출 할 때마다 고유 한 값입니다 .

이 값의 문제점은 HTML에서 ID가 알파벳 문자로 시작해야하기 때문에 요소의 ID로 사용할 수 없다는 것입니다. 두 사용자가 동시에 작업을 수행하면 동일한 ID가 생성 될 수 있다는 문제도 있습니다. ID의 숫자 부분 앞에 임의의 문자를 추가하여 그 확률을 줄이고 알파벳 문자 문제를 해결할 수 있습니다.

var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
var uniqid = randLetter + Date.now();

그래도 충돌 할 가능성은 희박 합니다. 고유 ID에 대한 최선의 방법은 실행 횟수를 유지하고 매번 증가하며 모든 작업을 단일 위치, 즉 서버에서 수행하는 것입니다.


다음은 임의의 ID를 생성하는 재사용 가능한 함수입니다.

function revisedRandId() {
     return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}

// 임의의 숫자로 시작하지 않으므로 CSS3에서 지원합니다.


여기에있는 사람들 중 일부는 귀하의 특정 질문에 실제로 초점을 맞추지 않은 것 같습니다. 문제는 페이지에 임의의 숫자를 넣고 플레이어를 연결하는 것입니다. 이를 수행하는 방법에는 여러 가지가 있습니다. 가장 간단한 방법은 페이지에 결과를 document.write ()와 같이 기존 코드를 약간 변경하는 것입니다. 일반적으로 document.write ()를 권장하지는 않지만 코드가 이미 인라인되어 있고 이미 시도한 것은 div를 인라인하는 것이기 때문에 이것이 가장 간단한 방법입니다. 임의의 숫자가있는 지점에서 이것을 사용하여 페이지에 div와 div를 넣습니다.

var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');

그런 다음 jwplayer 설정 코드에서 다음과 같이 참조합니다.

jwplayer(randomId).setup({

그리고 전체 코드 블록은 다음과 같습니다.

<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    var str = '';
    for (var i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
}

var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>'); 

  jwplayer(randomId).setup({
    'flashplayer': 'player.swf',
    'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
    'controlbar': 'bottom',
    'width': '470',
    'height': '320'
  });
</script>

그것을하는 또 다른 방법

I might add here at the end that generating a truly random number just to create a unique div ID is way overkill. You don't need a random number. You just need an ID that won't otherwise exist in the page. Frameworks like YUI have such a function and all they do is have a global variable that gets incremented each time the function is called and then combine that with a unique base string. It can look something like this:

var generateID = (function() {
    var globalIdCounter = 0;
    return function(baseStr) {
        return(baseStr + globalIdCounter++);
    }
})();

And, then in practical use, you would do something like this:

var randomId = generateID("myMovieContainer");  // "myMovieContainer1"
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({

I also needed a random id, I went with using base64 encoding:

btoa(Math.random()).substring(0,12)

Pick however many characters you want, the result is usually at least 24 characters.


Based on HTML 4, the id should start from letter:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

So, one of the solutions could be (alphanumeric):

  var length = 9;
  var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter

  // Convert it to base 36 (numbers + letters), and grab the first 9 characters
  // after the decimal.
  var id = prefix + Math.random().toString(36).substr(2, length);

Another solution - generate string with letters only:

  var length = 9;
  var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);

A edited version of @jfriend000 version:

    /**
     * Generates a random string
     * 
     * @param int length_
     * @return string
     */
    function randomString(length_) {

        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
        if (typeof length_ !== "number") {
            length_ = Math.floor(Math.random() * chars.length_);
        }
        var str = '';
        for (var i = 0; i < length_; i++) {
            str += chars[Math.floor(Math.random() * chars.length)];
        }
        return str;
    }

I would suggest that you start with some sort of placeholder, you may have this already, but its somewhere to append the div.

<div id="placeholder"></div>

Now, the idea is to dynamically create a new div, with your random id:

var rndId = randomString(8); 
var div = document.createElement('div');
div.id = rndId
div.innerHTML = "Whatever you want the content of your div to be";

this can be apended to your placeholder as follows:

document.getElementById('placeholder').appendChild(div);

You can then use that in your jwplayer code:

jwplayer(rndId).setup(...);

Live example: http://jsfiddle.net/pNYZp/

Sidenote: Im pretty sure id's must start with an alpha character (ie, no numbers) - you might want to change your implementation of randomstring to enforce this rule. (ref)


First. Assign an id to your div. Like this:

<div id="uniqueid">This text will be replaced</div>

After that, add inside your <script> tag following code:

Document.getElementById("uniqueid").id = randomString(8);

참고URL : https://stackoverflow.com/questions/6860853/generate-random-string-for-div-id

반응형