簡體   English   中英

新創建的 HTML 元素的動態 ID

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

我正在用選項框替換表格> td 內的跨度。 我想在創建選項框時分配一些具有動態值的唯一 id。 如何實現這一目標?

已生成唯一 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>";
});

例如,我將從變量中獲取一些值並將其分配給變量,然后將該變量分配給 id。

var myId = "OptionId"+test;

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

謝謝

在字符串中使用變量,如下所示:

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

確保分配唯一值的一種可能方法是跟蹤所有可用的 id 並分配一個不在我們列表中的 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;
}

可能的解決方案:

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

為其他人查看這些問題: 鏈接鏈接

自發布以來已經有幾年了,接受的解決方案對我不起作用。 這是這樣做的語法:

[id]="unqiueID"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM