简体   繁体   English

新创建的 HTML 元素的动态 ID

[英]Dynamic id for HTML element which is getting created newly

I am replacing a span inside a table > td with option box.我正在用选项框替换表格> td 内的跨度。 I want to assign some unique id with dynamic value while creating the option box.我想在创建选项框时分配一些具有动态值的唯一 id。 How to achieve this?如何实现这一目标?

Unique id is already generated , I want to set this unique id in Html while creation.已生成唯一 ID,我想在创建时在 Html 中设置此唯一 ID。

<td id="tdTest">
    <span id="spanId" class="connectedSlot" style="color:rgb(27,99,173)">Enabled</span>
</td>

$("#"+spanId).replaceWith(function () {
        return "<select class='form-control' id=<<DYNAMIC ID>> style='width:200px;'><option value='0'>Enabled</option><option value='1'>Disabled</option></select>";
});

For example , I will get some value from and assign to a variable and later assign this variable to id.例如,我将从变量中获取一些值并将其分配给变量,然后将该变量分配给 id。

var myId = "OptionId"+test;

select class='form-control' id=myId style='width:200px;'>

Thanks谢谢

Use a variable within a string like this:在字符串中使用变量,如下所示:

var unqiueID = "myID123", ret = "";
ret = "<select class='form-control' id='" + unqiueID +"' style='width:200px;'>";

One possible way to ensure that a unique value is assigned is to keep track of all the available id's and assign an id which isn't there in our list.确保分配唯一值的一种可能方法是跟踪所有可用的 id 并分配一个不在我们列表中的 id。

getUniqueId() is a function that will always return a unique id. getUniqueId()是一个始终返回唯一 ID 的函数。

function getUniqueId() {

    //get all the ids in this document
    var ids = new Array();
    $('[id]').each(function() { //Get elements that have an id=
      ids.push($(this).attr("id")); //add id to array
    });


    //give some random value to uniqueId
    //if this value is in ids array, then assign a different id and recheck the condition
    var uniqueId;
    while(true) {
        uniqueId = 'some-prefix-' + Math.floor(Math.random() * 10000);
        if($.inArray(uniqueId , ids) == -1) {
            break;
        }
    }
    return uniqueId;
}

Possible Solution:可能的解决方案:

function randomString(length) {
    return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}

Look into these Questions for others: link link为其他人查看这些问题: 链接链接

It's been several years since this was posted, and the accepted solution didn't work for me.自发布以来已经有几年了,接受的解决方案对我不起作用。 Here is the syntax that did:这是这样做的语法:

[id]="unqiueID" [id]="unqiueID"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM