Javascript 使用javascript创建唯一ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3231459/
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-23 03:46:20  来源:igfitidea点击:

create unique id with javascript

javascripthtmlselectdynamic

提问by JamesTBennett

I have a form where a user can add multiple select boxes for multiple cities. The problem is that each newly generated select box needs to have a unique id. Can this be done is JavaScript?

我有一个表单,用户可以在其中为多个城市添加多个选择框。问题是每个新生成的选择框都需要有一个唯一的 id。JavaScript 可以做到这一点吗?

UPDATE: here is the part of the form for selecting cities. Also note that i'm using some php to fill in the cities when a specific state is selected.

更新:这是选择城市的表格的一部分。Also note that i'm using some php to fill in the cities when a specific state is selected.

<form id="form" name="form" method="post" action="citySelect.php">
<select id="state" name="state" onchange="getCity()">
    <option></option>
    <option value="1">cali</option>
    <option value="2">arizona</option>
    <option value="3">texas</option>
</select>
<select id="city" name="city" style="width:100px">

</select>

    <br/>
</form>

Here is the javascript:

这是javascript:

$("#bt").click(function() {

$("#form").append(
       "<select id='state' name='state' onchange='getCity()'>
           <option></option>
           <option value='1'>cali</option>
           <option value='2'>arizona</option>
           <option value='3'>texas</option>
        </select>
        <select id='city' name='city' style='width:100px'></select><br/>"
     );
});

采纳答案by Jonathan Fingland

could you not just keep a running index?

你不能只保留一个正在运行的索引吗?

var _selectIndex = 0;

...code...
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);

EDIT

编辑

Upon further consideration, you may actually prefer to use array-style names for your selects...

经过进一步考虑,您实际上可能更喜欢为您的选择使用数组样式的名称...

e.g.

例如

<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>

then, on the server side in php for example:

然后,在 php 的服务器端,例如:

$cities = $_POST['city']; //array of option values from selects

EDIT 2In response to OP comment

编辑 2回应 OP 评论

Dynamically creating options using DOM methods can be done as follows:

可以按如下方式使用 DOM 方法动态创建选项:

var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);

var city = null,city_opt=null;
for (var i=0, len=cities.length; i< len; i++) {
    city = cities[i];
    var city_opt = document.createElement("option");
    city_opt.setAttribute("value",city);
    city_opt.appendChild(document.createTextNode(city));
    newSelectBox.appendChild(city_opt);
}
document.getElementById("example_element").appendChild(newSelectBox);

assuming that the citiesarray already exists

假设cities数组已经存在

Alternatively you could use the innerHTML method.....

或者,您可以使用 innerHTML 方法.....

var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
document.getElementById("example_element").appendChild(newSelectBox);

var city = null,htmlStr="";
for (var i=0, len=cities.length; i< len; i++) {
    city = cities[i];
    htmlStr += "<option value='" + city + "'>" + city + "</option>";
}
newSelectBox.innerHTML = htmlStr;

回答by Scott Evernden

another way it to use the millisecond timer:

使用毫秒计时器的另一种方式:

var uniq = 'id' + (new Date()).getTime();

回答by Fabio Montefuscolo

var id = "id" + Math.random().toString(16).slice(2)

回答by Guy Thomas

function uniqueid(){
    // always start with a letter (for DOM friendlyness)
    var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65));
    do {                
        // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
        var ascicode=Math.floor((Math.random()*42)+48);
        if (ascicode<58 || ascicode>64){
            // exclude all chars between : (58) and @ (64)
            idstr+=String.fromCharCode(ascicode);    
        }                
    } while (idstr.length<32);

    return (idstr);
}

回答by Junaid Atari

Very short function will give you unique ID:

很短的函数会给你唯一的ID:

var uid = (function(){var id=0;return function(){if(arguments[0]===0)id=0;return id++;}})();

alert ( uid() );

警报 ( uid() );

回答by molokoloco

In reply to @scott : Sometime JS go very fast... so...

回复@scott : 有时 JS 运行得非常快......所以......

var uniqueId = null,
    getUniqueName = function(prefix) {
        if (!uniqueId) uniqueId = (new Date()).getTime();
        return (prefix || 'id') + (uniqueId++);
    };

回答by fedeghe

put in your namespace an instance similar to the following one

在您的命名空间中放置一个类似于以下实例的实例

var myns = {/*.....*/};
myns.uid = new function () {
    var u = 0;
    this.toString = function () {
        return 'myID_' + u++;
    };
};
console.dir([myns.uid, myns.uid, myns.uid]);

回答by yodarunamok

I'm working on a similar problem to the OP, and found that elements of the solutions from @Guy and @Scott can be combined to create a solution that's more solid IMO. The resulting unique id here has three sections separated by underscores:

我正在研究与 OP 类似的问题,并发现 @Guy 和 @Scott 的解决方案元素可以结合起来创建一个更可靠的 IMO 解决方案。此处生成的唯一 id 由三个部分用下划线分隔:

  1. A leading letter;
  2. A timestamp displayed in base 36;
  3. And a final, random section.
  1. 一封领先的信件;
  2. 以 36 进制显示的时间戳;
  3. 以及最后的随机部分。

This solution should work really well, even for very large sets:

即使对于非常大的集合,该解决方案也应该非常有效:

function uniqueId () {
    // desired length of Id
    var idStrLen = 32;
    // always start with a letter -- base 36 makes for a nice shortcut
    var idStr = (Math.floor((Math.random() * 25)) + 10).toString(36) + "_";
    // add a timestamp in milliseconds (base 36 again) as the base
    idStr += (new Date()).getTime().toString(36) + "_";
    // similar to above, complete the Id using random, alphanumeric characters
    do {
        idStr += (Math.floor((Math.random() * 35))).toString(36);
    } while (idStr.length < idStrLen);

    return (idStr);
}

回答by Matthias H.

const uid = function(){
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

This Function generates very unique IDs that are sorted by its generated Date. Also useable for IDs in Databases.

此函数生成非常独特的 ID,按其生成日期排序。也可用于数据库中的 ID。

回答by YakovL

To avoid creating any counters and be sure that the id is unique even if there are some other components that create elements with ids on the page, you can use a random number and than correct it if it's not good enough (but you also have to set the id immediately to avoid conflicts):

为了避免创建任何计数器并确保 id 是唯一的,即使有一些其他组件在页面上创建带有 id 的元素,您可以使用随机数,如果它不够好,则可以更正它(但您也必须立即设置 id 以避免冲突):

var id = "item"+(new Date()).getMilliseconds()+Math.floor(Math.random()*1000);
 // or use any random number generator
 // whatever prefix can be used instead of "item"
while(document.getElementById(id))
    id += 1;
//# set id right here so that no element can get that id between the check and setting it