创建具有唯一 ID 的动态 div - jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3416227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:25:14  来源:igfitidea点击:

Create Dynamic div with unique IDs - jQuery

jquerydynamichtml

提问by Carson

Let me know if I'm not explaining this well enough as I'm confusing myself just thinking about it.

如果我没有很好地解释这一点,请告诉我,因为我只是在思考它而使自己感到困惑。

I was to be able to click on a button that says "add product" and have it create a unique div each time. For example, the first div would have the id #product1, then #product2 etc.

我能够点击一个显示“添加产品”的按钮,并让它每次都创建一个唯一的 div。例如,第一个 div 的 id 为 #product1,然后是 #product2 等。

The really tricky part is to have two input fields in the div, both regular text inputs. These also need to have unique IDs so I can use what is placed in them.

真正棘手的部分是在 div 中有两个输入字段,都是常规文本输入。这些还需要具有唯一的 ID,以便我可以使用放置在其中的内容。

Let me know if you have any solutions. Thanks, Carson

如果您有任何解决方案,请告诉我。谢谢,卡森

回答by Nick Craver

You can just use an incrementing ID variable, like this:

您可以只使用递增的 ID 变量,如下所示:

var i = 1;
$("#addProduct").click(function() {
  $("<div />", { "class":"wrapper", id:"product"+i })
     .append($("<input />", { type: "text", id:"name"+i }))
     .append($("<input />", { type: "text", id:"property"+i }))
     .appendTo("#someContainer");
  i++;
});

You can give it a try here, this is a very general answer, but you get the idea, just increment the variable after adding your items each time.

你可以在这里试一试,这是一个非常笼统的答案,但你明白了,每次添加你的项目后只增加变量。

回答by rodiwa

Ok. This is a really old post but I thought it might help if you're having a similar issue. I came across the .uniqueId() in jQuery (see here).

好的。这是一个非常古老的帖子,但我认为如果您遇到类似的问题,它可能会有所帮助。我在 jQuery 中遇到了 .uniqueId() (请参阅此处)。

It checks whether the element already has an id or not and if it doesn't, it assigns a unique id to it. The drawback is that you cannot have a 'custom id name' to it (such as product_1, product_2, etc). The id assigned is something like ui-id-1, ui-id-2, etc.

它检查元素是否已经有一个 id,如果没有,它会为它分配一个唯一的 id。缺点是您不能为其指定“自定义 ID 名称”(例如 product_1、product_2 等)。分配的 id 类似于 ui-id-1、ui-id-2 等。

To assign a unique id, you can so something like this -

要分配一个唯一的 id,你可以这样 -

$("<div class='someDivConntet'></div>").insertAfter($(this)).uniqueId(); 

Just make sure you don't have an id set on the element already.

只需确保您尚未在元素上设置 id。

回答by jAndy

$(function(){
    var pcount = icount = 0;

    $('<div/>', {
       id:   'product' + pcount++
    }).append($('<input/>', {
       id:   'input' + icount++
    })).append($('<input/>', {
       id:   'input' + icount++
    })).appendTo(document.body);
});

回答by Gareth

Generally you don't need to use IDs in this way.

通常,您不需要以这种方式使用 ID。

Once you've created the new element using Javascript, you already have an object which you can pass around, into functions etc. You certainly don't need to pass the ID around just so that you can pass it into document.getElementByID()

一旦您使用 Javascript 创建了新元素,您就已经拥有了一个可以传递给函数等的对象。您当然不需要传递 ID 以便您可以将它传递给 document.getElementByID()

回答by pie6k

I'm using this one I've made

我正在使用我制作的这个

$.fn.uniqueId = function(idlength){
    var charstoformid = '_0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
    if (! idlength) idlength = 10;

    var getId = function() {
        var uniqid = '';
        for (var i = 0; i < idlength; i++) {
            uniqid += charstoformid[Math.floor(Math.random() * charstoformid.length)];
        }
        return uniqid;
    }

    return $(this).each(function(){
        var id = getId()

        while ( $("#"+id).length ) {
            id = getId();
        }
        $(this).attr("id", id);         
    });
}

It has function to generate random chars chain, then it make sure that generated one is unique (that has 0,000001% of possibility - but it's possible) and then change id.

它具有生成随机字符链的功能,然后它确保生成的一个是唯一的(有 0,000001% 的可能性 - 但它是可能的),然后更改 id。

回答by Rathod Paresh

You can used Just increase variable and append to create unique DIV ID Code As like Bellow

您可以使用 Just 增加变量并追加来创建唯一的 DIV ID 代码,就像 Bellow

var x = 1;
var wrapper = $('.field_wrapper'); //Input field wrapper your div Add in this Class


var fieldtext = '<div ID="product_'+x+'"><label id="label_'+x+'" for="field_'+x+'"></label><input type="text" id="field_'+x+'" name="field_'+x+'" value=""/></div>'; //New input field html 

$(wrapper).append(fieldtext); // Add field html
x++;