【问题标题】:On button click create dynamic drop down lists with unique id's in JavaScript单击按钮时,在 JavaScript 中创建具有唯一 ID 的动态下拉列表
【发布时间】:2021-01-10 01:57:01
【问题描述】:

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

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

这是我创建 ddls 的代码:

<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);
}

谢谢你☺️

【问题讨论】:

  • 您似乎从 HTML 中省略了一些元素。此外,您在声明函数时有一个错字。 function 关键字应为小写。
  • 我已经更新了代码,所以目前 onclick="OW_LO_LW()" 它正在创建多个 DDl 我想添加代码为每个 DDL 添加唯一 ID。

标签: javascript jquery dynamic drop-down-menu unique-id


【解决方案1】:

您可以像这样data-number=0 向containerOWL 添加data attribute

现在在函数调用中,您可以简单地获取该数字并将其加一并将该值赋予该选择 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)
}

【讨论】:

  • 您好,感谢您的评论,您的代码对我有帮助。你能告诉我数据编号的脚本吗,因为目前它正在使用 NaN。
  • 哦,这很简单,&lt;div class="form-group" id="containerOWL" data-number=0&gt; 如果它解决了您的问题,请接受答案。谢谢
猜你喜欢
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 2016-12-04
  • 2016-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
相关资源
最近更新 更多