3

按下时我有一个按钮会创建新的输入栏,我希望这些输入栏具有唯一的 ID,例如 - textBar1、textBar2、textBar3 等。

我尝试在函数外部创建一个值为 0 的变量,然后在函数内部为函数每次运行时添加 +1 的值,但这不起作用,而是将 id textBar0 分配给创建的每个元素.

有人对如何解决这个问题有任何建议吗?

提前致谢!

HTML

<label for='ingredient'></label>
<input id="textBar" class="textBar" type="name" name="ingredient">

<div id="textBarPosition"></div>
<div id="addRemoveContainer">

<input id="addBar" type="button" value="Add Ingredient">

JavaScript/jQuery

   var counter = 0;
function createSector() {
  var input = document.createElement('input'); 
  input.setAttribute("id", 'textBar' + counter +1);
  input.type = 'text';
  input.name = 'name[]';
  return input;
counter = 1;

}


var form = document.getElementById('textBarPosition');
document.getElementById('addBar').addEventListener('click', function(e) {
    // step 1: create element and set opacity to 0.
    var selector = $(createSector());
    selector.fadeIn();

   // step 2: append it to its parent.
    $(form).append(selector);

    $('#removeBar').click(function(){
        $("input:last-child").remove(".textBar");
    });
});
4

4 回答 4

5

那是因为您没有将更改后的值重新评估为counter. 改为使用counter+=1或仅使用counter++

input.setAttribute("id", 'textBar' + counter++); // now it should work

你之前所做的总是添加10

于 2014-10-09T12:54:47.683 回答
3

最好的方法是使用_.uniqueId

为需要的客户端模型或 DOM 元素生成一个全局唯一的 id。如果前缀被传递,id 将被附加到它上面。

_.uniqueId('contact_');
=> 'contact_104'
于 2014-12-10T06:43:23.427 回答
2

你可以Math.random这样使用:

input.setAttribute("id", 'textBar_' + Math.random().toString(36));

据我了解,当您第一次调用Math.random它时,它会使用当前时间(以毫秒为单位)作为种子生成 0 到 1 之间的唯一随机数序列,然后返回第一个。随后的调用将遍历生成的数字序列,一次返回一个,使您能够为元素 ID 生成随机的唯一字符串。

于 2014-10-09T13:36:25.880 回答
0

jQuery 代码 -

  var counter = 0;
function createSector() {
  var input = document.createElement('input'); 
  input.setAttribute("id", 'textBar' + counter);
  input.type = 'text';
  input.name = 'name[]';
  return input;


}

var form = document.getElementById('textBarPosition');
document.getElementById('addBar').addEventListener('click', function(e) {
    // step 1: create element and set opacity to 0.
    var selector = $(createSector());
    counter++;
    selector.fadeIn();

   // step 2: append it to its parent.
    $(form).append(selector);

    $('#removeBar').click(function(){
        $("input:last-child").remove(".textBar");
    });
});

工作 JSFiddle - http://jsfiddle.net/Ashish_developer/mtafre04/

于 2014-10-09T12:59:01.453 回答