web-dev-qa-db-ja.com

一意のIDで動的divを作成する-jQuery

考えているだけで混乱しているので、これを十分に説明していない場合はお知らせください。

「製品を追加」というボタンをクリックして、毎回一意のdivを作成できるようにする必要がありました。たとえば、最初のdivのIDは#product1、次に#product2などになります。

本当にトリッキーな部分は、divに2つの入力フィールドがあり、どちらも通常のテキスト入力であるということです。これらには、配置されているものを使用できるように、一意のIDも必要です。

解決策があれば教えてください。ありがとう、カーソン

11
Carson

次のように、増分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++;
});

ここで試してみることができます 、これは非常に一般的な答えですが、アイデアは得られます。毎回アイテムを追加した後、変数をインクリメントするだけです。

19
Nick Craver

OK。これは本当に古い投稿ですが、同様の問題が発生している場合に役立つと思いました。 jQueryで.uniqueId()に出くわしました( ここを参照 )。

要素にすでにIDがあるかどうかを確認し、持っていない場合は、一意のIDを割り当てます。欠点は、「カスタムID名」(product_1、product_2など)を設定できないことです。割り当てられるIDは、ui-id-1、ui-id-2などです。

一意のIDを割り当てるには、次のようにします-

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

要素にIDがまだ設定されていないことを確認してください。

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

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

通常、この方法でIDを使用する必要はありません。

Javascriptを使用して新しい要素を作成すると、関数などに渡すことができるオブジェクトがすでに作成されています。document.getElementByID()に渡すためだけにIDを渡す必要はありません。

1
Gareth

私が作ったこれを使っています

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

ランダムなcharsチェーンを生成する機能があり、生成されたものが一意であることを確認し(0,000001%の可能性がありますが、可能です)、idを変更します。

0
pie6k

変数を増やして追加するだけで、Bellowのように一意のDIVIDコードを作成できます。

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++;
0
Rathod Paresh