在按钮上,单击“在JavaScript中创建具有唯一id的动态下拉列表”

在按钮上,单击“在JavaScript中创建具有唯一id的动态下拉列表”,javascript,jquery,dynamic,drop-down-menu,unique-id,Javascript,Jquery,Dynamic,Drop Down Menu,Unique Id,我想在单击按钮时创建多个动态下拉列表。。 每个添加的下拉列表都应该有一个唯一的ID 我有一段代码可以创建多个下拉列表,但我不知道如何添加代码来创建DDL的唯一ID 以下是我创建DDL的代码: <div class="col-md-4"> <div class="form-group" id="containerOWL"> // I want to add dynamic drop down list here &

我想在单击按钮时创建多个动态下拉列表。。 每个添加的下拉列表都应该有一个唯一的ID

我有一段代码可以创建多个下拉列表,但我不知道如何添加代码来创建DDL的唯一ID

以下是我创建DDL的代码:

<div class="col-md-4">
<div class="form-group" id="containerOWL">
// I want to add dynamic drop down list here
</div>
</div>

<div class="row" style="margin-bottom: 32px;">
<a class="btn btn-primary" onclick="OW_LO_LW()" style="margin: 0 0 0 15px;">+ Add OWL/LO/LW</a>
</div>

function OW_LO_LW() {
var drop_list = '<select class="form-control">';
drop_list += '<option selected disabled >Select</option>';
drop_list += '<option >FL</option>';
drop_list += '<option >GA</option>';
drop_list += '<option >AL</option>';
drop_list += '</select>';
$("#containerOWL").append(drop_list);
}
多谢各位☺️

您可以向ContainerWL添加数据属性,如数据编号=0

现在在函数调用中,您可以简单地获取该数字并将其增加1,然后将该值赋予该select id,最后增加该数据属性值

完整代码:

function OW_LO_LW() {
    containerOWL = $("#containerOWL")

    const currValue = containerOWL.data("number")
    const nextValue = currValue + 1

    var drop_list = `<select id="${nextValue}" class="form-control">`;
    drop_list += '<option selected disabled >Select</option>';
    drop_list += '<option >FL</option>';
    drop_list += '<option >GA</option>';
    drop_list += '<option >AL</option>';
    drop_list += '</select>';
    containerOWL.append(drop_list);

    containerOWL.data("number", nextValue)
}

您似乎从HTML中省略了一些元素。此外,您在声明函数时也有输入错误。function关键字应该是小写的。我已经更新了代码,所以当前onclick=OW_LO_LW它正在创建多个DDl。我想添加代码为每个DDl添加唯一的ID。嘿,谢谢你的评论,你的代码正在帮助我。你能让我知道数据编号的脚本吗,因为目前它需要NaN。哦,它非常简单,如果它解决了你的问题,请接受答案。谢谢